From 29bfa9aed607e8a6d647e45d441ae34746ebdcd5 Mon Sep 17 00:00:00 2001 From: Drew Angell Date: Sun, 20 Apr 2025 18:38:09 -0500 Subject: [PATCH 001/146] Removes old REST framework, 219 --- composer.json | 3 +- .../CreatePaymentUsingPayPal.php | 96 -- .../ExecutePayment.php | 51 - .../GetPaymentDetails.php | 131 -- .../rest-checkout-line-items-v1/index.php | 190 --- .../order-complete.php | 167 --- .../rest-checkout-line-items-v1/review.php | 147 -- .../CaptureOrder.php | 40 - .../CreateCaptureOrder.php | 122 -- .../GetOrderDetails.php | 148 -- .../rest-checkout-line-items-v2/index.php | 217 --- .../order-complete.php | 152 -- .../rest-checkout-line-items-v2/review.php | 152 -- .../BillAgreementBalance.php | 24 - .../CancelBillingAgreement.php | 24 - .../CreateBillingAgreementWithCreditCard.php | 74 - .../CreateBillingAgreementWithPayPal.php | 51 - .../billing_agreements/ExecuteAgreement.php | 28 - .../GetBillingAgreement.php | 21 - .../ReactivateBillingAgreement.php | 22 - .../SearchBillingTransactions.php | 26 - .../SetAgreementBalance.php | 26 - .../SuspendBillingAgreement.php | 21 - .../UpdateBillingAgreement.php | 32 - samples/rest/billing_plans/CreatePlan.php | 110 -- samples/rest/billing_plans/DeletePlan.php | 21 - samples/rest/billing_plans/GetPlan.php | 21 - samples/rest/billing_plans/ListPlans.php | 25 - samples/rest/billing_plans/UpdatePlan.php | 28 - .../rest/checkout_orders/AuthorizeOrder.php | 45 - .../CaptureAuthorizedPayment.php | 69 - samples/rest/checkout_orders/CaptureOrder.php | 43 - .../checkout_orders/CreateAuthorizeOrder.php | 211 --- .../checkout_orders/CreateCaptureOrder.php | 211 --- .../GetAuthorizePaymentDetails.php | 26 - .../GetCapturedPaymentDetails.php | 26 - .../rest/checkout_orders/GetOrderDetails.php | 26 - samples/rest/checkout_orders/Reauthorize.php | 30 - .../checkout_orders/RefundCapturedPayment.php | 41 - .../checkout_orders/ShowRefundDetails.php | 26 - samples/rest/checkout_orders/UpdateOrder.php | 52 - .../checkout_orders/VoidAuthorizedPayment.php | 26 - .../rest/customer-disputes/AcceptClaim.php | 62 - .../rest/customer-disputes/DisputesAppeal.php | 81 - .../customer-disputes/DisputesEscalate.php | 27 - .../customer-disputes/DisputesMakeOffer.php | 56 - .../rest/customer-disputes/ListDisputes.php | 34 - .../customer-disputes/ProvideEvidence.php | 85 -- .../SendMessageToOtherParty.php | 27 - .../rest/customer-disputes/SettleDispute.php | 35 - .../customer-disputes/ShowDisputeDetails.php | 23 - .../customer-disputes/UpdateDisputeStatus.php | 44 - samples/rest/identity/GetUserConsentURL.php | 43 - samples/rest/identity/GetUserInfo.php | 34 - samples/rest/identity/UserConsentRedirect.php | 29 - .../CreateInvoiceTemplate.php | 180 --- .../DeleteInvoiceTemplate.php | 20 - .../GetAllInvoiceTemplates.php | 22 - .../invoice-templates/GetInvoiceTemplate.php | 20 - .../UpdateInvoiceTemplate.php | 183 --- samples/rest/invoice/CancelInvoice.php | 28 - samples/rest/invoice/CreateInvoice.php | 207 --- .../rest/invoice/CreateThirdPartyInvoice.php | 221 --- samples/rest/invoice/DeleteInvoice.php | 20 - samples/rest/invoice/GetInvoice.php | 20 - samples/rest/invoice/GetNextInvoiceNumber.php | 18 - samples/rest/invoice/GetThirdPartyInvoice.php | 31 - samples/rest/invoice/ListInvoice.php | 24 - samples/rest/invoice/RecordPayment.php | 31 - samples/rest/invoice/RecordRefund.php | 39 - samples/rest/invoice/RemindInvoice.php | 28 - samples/rest/invoice/RetrieveQRCode.php | 29 - samples/rest/invoice/SearchInvoices.php | 38 - samples/rest/invoice/SendInvoice.php | 20 - samples/rest/invoice/UpdateInvoice.php | 179 --- samples/rest/invoice/images/sample.png | Bin 625 -> 0 bytes samples/rest/invoice_v2/CancelInvoice.php | 31 - samples/rest/invoice_v2/DeleteInvoice.php | 23 - samples/rest/invoice_v2/GetInvoice.php | 23 - .../rest/invoice_v2/GetNextInvoiceNumber.php | 21 - samples/rest/invoice_v2/ListInvoice.php | 27 - samples/rest/invoice_v2/SendInvoice.php | 23 - samples/rest/notifications/CreateWebhook.php | 31 - samples/rest/notifications/DeleteWebhook.php | 26 - .../EventNotificationDetails.php | 22 - samples/rest/notifications/GetWebhook.php | 24 - .../ListEventSubscriptionsForWebhook.php | 22 - samples/rest/notifications/ListWebhooks.php | 22 - .../rest/notifications/PayPal_Webhooks.txt | 67 - .../notifications/ResendEventNotification.php | 22 - .../notifications/SearchWebhookEvents.php | 28 - samples/rest/notifications/SimulateEvent.php | 27 - samples/rest/notifications/UpdateWebhook.php | 38 - .../notifications/VerifyWebhookSignature.php | 32 - .../rest/notifications/WebhooksEventTypes.php | 20 - samples/rest/payment/AuthorizationCapture.php | 25 - .../payment/AuthorizePaymentUsingPayPal.php | 100 -- samples/rest/payment/CreateFuturePayment.php | 106 -- samples/rest/payment/CreatePayment.php | 108 -- .../rest/payment/CreatePaymentUsingPayPal.php | 89 -- .../CreatePaymentUsingSavedCardVault.php | 73 - .../rest/payment/CreateThirdPartyPayment.php | 102 -- samples/rest/payment/ExecutePayment.php | 64 - samples/rest/payment/GetAuthorization.php | 21 - samples/rest/payment/GetCapture.php | 20 - samples/rest/payment/ListPayments.php | 35 - samples/rest/payment/OrderAuthorize.php | 49 - samples/rest/payment/OrderCapture.php | 49 - .../payment/OrderCreateForAuthorization.php | 89 -- .../rest/payment/OrderCreateForCapture.php | 89 -- samples/rest/payment/OrderCreateForVoid.php | 89 -- samples/rest/payment/OrderDoVoid.php | 44 - samples/rest/payment/OrderGet.php | 21 - samples/rest/payment/Reauthorization.php | 47 - samples/rest/payment/RefundCapture.php | 36 - samples/rest/payment/ShowPaymentDetails.php | 23 - samples/rest/payment/ShowRefundDetails.php | 23 - samples/rest/payment/UpdatePayment.php | 62 - samples/rest/payment/VoidAuthorization.php | 20 - .../paymentexperience/CreateWebProfile.php | 56 - .../paymentexperience/DeleteWebProfile.php | 22 - .../rest/paymentexperience/GetWebProfile.php | 25 - .../paymentexperience/ListWebProfiles.php | 23 - .../PartiallyUpdateWebProfile.php | 41 - .../paymentexperience/UpdateWebProfile.php | 58 - samples/rest/payouts/CancelPayoutItem.php | 23 - samples/rest/payouts/CreateBatchPayout.php | 76 - samples/rest/payouts/CreateSinglePayout.php | 53 - samples/rest/payouts/GetPayoutBatchStatus.php | 26 - samples/rest/payouts/GetPayoutItemStatus.php | 26 - .../paypal_sync/PaypalSyncTransactions.php | 43 - .../CreateReferencedBatchPayout.php | 102 -- samples/rest/sale/GetSale.php | 26 - samples/rest/sale/RefundSale.php | 46 - samples/rest/vault/DeleteCreditCard.php | 27 - samples/rest/vault/GetCardDetails.php | 26 - samples/rest/vault/ListCreditCards.php | 34 - samples/rest/vault/StoreCreditCard.php | 58 - samples/rest/vault/UpdateCreditCard.php | 88 -- .../PayPal/rest/billing/BillingAPI.php | 564 ------- .../checkout_orders/CheckoutOrdersAPI.php | 328 ----- .../customerdisputes/CustomerDisputesAPI.php | 302 ---- .../PayPal/rest/identity/IdentityAPI.php | 133 -- .../PayPal/rest/invoice/InvoiceAPI.php | 1281 ---------------- .../PayPal/rest/invoice/InvoiceAPIv2.php | 1298 ----------------- .../rest/notifications/NotificationsAPI.php | 394 ----- .../PaymentExperianceAPI.php | 248 ---- .../PayPal/rest/payments/PaymentAPI.php | 1296 ---------------- .../PayPal/rest/payouts/PayoutsAPI.php | 213 --- .../PayPal/rest/paypal_sync/PayPalSyncAPI.php | 86 -- .../ReferencedPayoutsAPI.php | 87 -- .../PayPal/rest/vault/CreditCardAPI.php | 219 --- .../BillAgreementBalance.php | 24 - .../CancelBillingAgreement.php | 21 - .../CreateBillingAgreementWithCreditCard.php | 73 - .../CreateBillingAgreementWithPayPal.php | 51 - .../billing_agreements/ExecuteAgreement.php | 28 - .../GetBillingAgreement.php | 21 - .../ReactivateBillingAgreement.php | 21 - .../SearchBillingTransactions.php | 26 - .../SetAgreementBalance.php | 26 - .../SuspendBillingAgreement.php | 22 - .../UpdateBillingAgreement.php | 34 - templates/rest/billing_plans/CreatePlan.php | 107 -- templates/rest/billing_plans/DeletePlan.php | 20 - templates/rest/billing_plans/GetPlan.php | 20 - templates/rest/billing_plans/ListPlans.php | 25 - templates/rest/billing_plans/UpdatePlan.php | 28 - .../rest/checkout_orders/AuthorizeOrder.php | 45 - .../CaptureAuthorizedPayment.php | 69 - .../rest/checkout_orders/CaptureOrder.php | 43 - .../checkout_orders/CreateAuthorizeOrder.php | 211 --- .../checkout_orders/CreateCaptureOrder.php | 211 --- .../GetAuthorizePaymentDetails.php | 26 - .../GetCapturedPaymentDetails.php | 26 - .../rest/checkout_orders/GetOrderDetails.php | 26 - .../rest/checkout_orders/Reauthorize.php | 30 - .../checkout_orders/RefundCapturedPayment.php | 41 - .../checkout_orders/ShowRefundDetails.php | 26 - .../checkout_orders/VoidAuthorizedPayment.php | 26 - .../rest/customer-disputes/AcceptClaim.php | 62 - .../rest/customer-disputes/DisputesAppeal.php | 81 - .../customer-disputes/DisputesEscalate.php | 27 - .../customer-disputes/DisputesMakeOffer.php | 56 - .../rest/customer-disputes/ListDisputes.php | 34 - .../customer-disputes/ProvideEvidence.php | 85 -- .../SendMessageToOtherParty.php | 27 - .../rest/customer-disputes/SettleDispute.php | 35 - .../customer-disputes/ShowDisputeDetails.php | 23 - .../customer-disputes/UpdateDisputeStatus.php | 44 - templates/rest/identity/GetUserConsentURL.php | 37 - templates/rest/identity/GetUserInfo.php | 34 - .../rest/identity/UserConsentRedirect.php | 29 - .../CreateInvoiceTemplate.php | 183 --- .../DeleteInvoiceTemplate.php | 20 - .../GetAllInvoiceTemplates.php | 22 - .../invoice-templates/GetInvoiceTemplate.php | 20 - .../UpdateInvoiceTemplate.php | 185 --- templates/rest/invoice/CancelInvoice.php | 28 - templates/rest/invoice/CreateInvoice.php | 168 --- .../rest/invoice/CreateThirdPartyInvoice.php | 212 --- templates/rest/invoice/DeleteInvoice.php | 20 - templates/rest/invoice/GetInvoice.php | 20 - .../rest/invoice/GetNextInvoiceNumber.php | 18 - .../rest/invoice/GetThirdPartyInvoice.php | 31 - templates/rest/invoice/ListInvoice.php | 24 - templates/rest/invoice/RecordPayment.php | 31 - templates/rest/invoice/RecordRefund.php | 38 - templates/rest/invoice/RemindInvoice.php | 28 - templates/rest/invoice/RetrieveQRCode.php | 30 - templates/rest/invoice/SearchInvoices.php | 38 - templates/rest/invoice/SendInvoice.php | 20 - templates/rest/invoice/UpdateInvoice.php | 176 --- .../rest/notifications/CreateWebhook.php | 31 - .../rest/notifications/DeleteWebhook.php | 26 - .../EventNotificationDetails.php | 22 - templates/rest/notifications/GetWebhook.php | 24 - .../ListEventSubscriptionsForWebhook.php | 22 - templates/rest/notifications/ListWebhooks.php | 22 - .../rest/notifications/PayPal_Webhooks.txt | 67 - .../notifications/ResendEventNotification.php | 22 - .../notifications/SearchWebhookEvents.php | 28 - .../rest/notifications/SimulateEvent.php | 27 - .../rest/notifications/UpdateWebhook.php | 34 - .../notifications/VerifyWebhookSignature.php | 31 - .../rest/notifications/WebhooksEventTypes.php | 20 - .../rest/payment/AuthorizationCapture.php | 25 - templates/rest/payment/CreatePayment.php | 104 -- .../rest/payment/CreatePaymentUsingPayPal.php | 82 -- .../CreatePaymentUsingSavedCardVault.php | 73 - .../rest/payment/CreateThirdPartyPayment.php | 101 -- templates/rest/payment/ExecutePayment.php | 64 - templates/rest/payment/GetAuthorization.php | 21 - templates/rest/payment/GetCapture.php | 20 - templates/rest/payment/ListPayments.php | 27 - templates/rest/payment/OrderAuthorize.php | 25 - templates/rest/payment/OrderCapture.php | 26 - templates/rest/payment/OrderDoVoid.php | 21 - templates/rest/payment/OrderGet.php | 48 - templates/rest/payment/Reauthorization.php | 47 - templates/rest/payment/RefundCapture.php | 42 - templates/rest/payment/ShowPaymentDetails.php | 23 - templates/rest/payment/ShowRefundDetails.php | 23 - templates/rest/payment/UpdatePayment.php | 61 - templates/rest/payment/VoidAuthorization.php | 21 - .../paymentexperience/CreateWebProfile.php | 53 - .../paymentexperience/DeleteWebProfile.php | 22 - .../rest/paymentexperience/GetWebProfile.php | 22 - .../paymentexperience/ListWebProfiles.php | 19 - .../PartiallyUpdateWebProfile.php | 38 - .../paymentexperience/UpdateWebProfile.php | 56 - templates/rest/payouts/CancelPayoutItem.php | 20 - templates/rest/payouts/CreateBatchPayout.php | 68 - templates/rest/payouts/CreateSinglePayout.php | 47 - .../rest/payouts/GetPayoutBatchStatus.php | 20 - .../rest/payouts/GetPayoutItemStatus.php | 20 - .../paypal_sync/paypal_sync_transactions.php | 43 - .../create_referenced_batch_payout.php | 99 -- templates/rest/sale/GetSale.php | 26 - templates/rest/sale/RefundSale.php | 46 - templates/rest/vault/DeleteCreditCard.php | 23 - templates/rest/vault/GetCardDetails.php | 23 - templates/rest/vault/ListCreditCards.php | 32 - templates/rest/vault/StoreCreditCard.php | 54 - templates/rest/vault/UpdateCreditCard.php | 85 -- 265 files changed, 1 insertion(+), 19439 deletions(-) delete mode 100644 demo/rest/rest-checkout-line-items-v1/CreatePaymentUsingPayPal.php delete mode 100644 demo/rest/rest-checkout-line-items-v1/ExecutePayment.php delete mode 100644 demo/rest/rest-checkout-line-items-v1/GetPaymentDetails.php delete mode 100644 demo/rest/rest-checkout-line-items-v1/index.php delete mode 100644 demo/rest/rest-checkout-line-items-v1/order-complete.php delete mode 100644 demo/rest/rest-checkout-line-items-v1/review.php delete mode 100644 demo/rest/rest-checkout-line-items-v2/CaptureOrder.php delete mode 100644 demo/rest/rest-checkout-line-items-v2/CreateCaptureOrder.php delete mode 100644 demo/rest/rest-checkout-line-items-v2/GetOrderDetails.php delete mode 100644 demo/rest/rest-checkout-line-items-v2/index.php delete mode 100644 demo/rest/rest-checkout-line-items-v2/order-complete.php delete mode 100644 demo/rest/rest-checkout-line-items-v2/review.php delete mode 100644 samples/rest/billing_agreements/BillAgreementBalance.php delete mode 100644 samples/rest/billing_agreements/CancelBillingAgreement.php delete mode 100644 samples/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php delete mode 100644 samples/rest/billing_agreements/CreateBillingAgreementWithPayPal.php delete mode 100644 samples/rest/billing_agreements/ExecuteAgreement.php delete mode 100644 samples/rest/billing_agreements/GetBillingAgreement.php delete mode 100644 samples/rest/billing_agreements/ReactivateBillingAgreement.php delete mode 100644 samples/rest/billing_agreements/SearchBillingTransactions.php delete mode 100644 samples/rest/billing_agreements/SetAgreementBalance.php delete mode 100644 samples/rest/billing_agreements/SuspendBillingAgreement.php delete mode 100644 samples/rest/billing_agreements/UpdateBillingAgreement.php delete mode 100644 samples/rest/billing_plans/CreatePlan.php delete mode 100644 samples/rest/billing_plans/DeletePlan.php delete mode 100644 samples/rest/billing_plans/GetPlan.php delete mode 100644 samples/rest/billing_plans/ListPlans.php delete mode 100644 samples/rest/billing_plans/UpdatePlan.php delete mode 100644 samples/rest/checkout_orders/AuthorizeOrder.php delete mode 100644 samples/rest/checkout_orders/CaptureAuthorizedPayment.php delete mode 100644 samples/rest/checkout_orders/CaptureOrder.php delete mode 100644 samples/rest/checkout_orders/CreateAuthorizeOrder.php delete mode 100644 samples/rest/checkout_orders/CreateCaptureOrder.php delete mode 100644 samples/rest/checkout_orders/GetAuthorizePaymentDetails.php delete mode 100644 samples/rest/checkout_orders/GetCapturedPaymentDetails.php delete mode 100644 samples/rest/checkout_orders/GetOrderDetails.php delete mode 100644 samples/rest/checkout_orders/Reauthorize.php delete mode 100644 samples/rest/checkout_orders/RefundCapturedPayment.php delete mode 100644 samples/rest/checkout_orders/ShowRefundDetails.php delete mode 100644 samples/rest/checkout_orders/UpdateOrder.php delete mode 100644 samples/rest/checkout_orders/VoidAuthorizedPayment.php delete mode 100644 samples/rest/customer-disputes/AcceptClaim.php delete mode 100644 samples/rest/customer-disputes/DisputesAppeal.php delete mode 100644 samples/rest/customer-disputes/DisputesEscalate.php delete mode 100644 samples/rest/customer-disputes/DisputesMakeOffer.php delete mode 100644 samples/rest/customer-disputes/ListDisputes.php delete mode 100644 samples/rest/customer-disputes/ProvideEvidence.php delete mode 100644 samples/rest/customer-disputes/SendMessageToOtherParty.php delete mode 100644 samples/rest/customer-disputes/SettleDispute.php delete mode 100644 samples/rest/customer-disputes/ShowDisputeDetails.php delete mode 100644 samples/rest/customer-disputes/UpdateDisputeStatus.php delete mode 100644 samples/rest/identity/GetUserConsentURL.php delete mode 100644 samples/rest/identity/GetUserInfo.php delete mode 100644 samples/rest/identity/UserConsentRedirect.php delete mode 100755 samples/rest/invoice-templates/CreateInvoiceTemplate.php delete mode 100755 samples/rest/invoice-templates/DeleteInvoiceTemplate.php delete mode 100755 samples/rest/invoice-templates/GetAllInvoiceTemplates.php delete mode 100755 samples/rest/invoice-templates/GetInvoiceTemplate.php delete mode 100755 samples/rest/invoice-templates/UpdateInvoiceTemplate.php delete mode 100755 samples/rest/invoice/CancelInvoice.php delete mode 100755 samples/rest/invoice/CreateInvoice.php delete mode 100644 samples/rest/invoice/CreateThirdPartyInvoice.php delete mode 100755 samples/rest/invoice/DeleteInvoice.php delete mode 100755 samples/rest/invoice/GetInvoice.php delete mode 100755 samples/rest/invoice/GetNextInvoiceNumber.php delete mode 100644 samples/rest/invoice/GetThirdPartyInvoice.php delete mode 100755 samples/rest/invoice/ListInvoice.php delete mode 100755 samples/rest/invoice/RecordPayment.php delete mode 100755 samples/rest/invoice/RecordRefund.php delete mode 100755 samples/rest/invoice/RemindInvoice.php delete mode 100755 samples/rest/invoice/RetrieveQRCode.php delete mode 100755 samples/rest/invoice/SearchInvoices.php delete mode 100755 samples/rest/invoice/SendInvoice.php delete mode 100755 samples/rest/invoice/UpdateInvoice.php delete mode 100755 samples/rest/invoice/images/sample.png delete mode 100644 samples/rest/invoice_v2/CancelInvoice.php delete mode 100644 samples/rest/invoice_v2/DeleteInvoice.php delete mode 100644 samples/rest/invoice_v2/GetInvoice.php delete mode 100644 samples/rest/invoice_v2/GetNextInvoiceNumber.php delete mode 100644 samples/rest/invoice_v2/ListInvoice.php delete mode 100644 samples/rest/invoice_v2/SendInvoice.php delete mode 100644 samples/rest/notifications/CreateWebhook.php delete mode 100644 samples/rest/notifications/DeleteWebhook.php delete mode 100644 samples/rest/notifications/EventNotificationDetails.php delete mode 100644 samples/rest/notifications/GetWebhook.php delete mode 100644 samples/rest/notifications/ListEventSubscriptionsForWebhook.php delete mode 100644 samples/rest/notifications/ListWebhooks.php delete mode 100644 samples/rest/notifications/PayPal_Webhooks.txt delete mode 100644 samples/rest/notifications/ResendEventNotification.php delete mode 100644 samples/rest/notifications/SearchWebhookEvents.php delete mode 100644 samples/rest/notifications/SimulateEvent.php delete mode 100644 samples/rest/notifications/UpdateWebhook.php delete mode 100644 samples/rest/notifications/VerifyWebhookSignature.php delete mode 100644 samples/rest/notifications/WebhooksEventTypes.php delete mode 100755 samples/rest/payment/AuthorizationCapture.php delete mode 100644 samples/rest/payment/AuthorizePaymentUsingPayPal.php delete mode 100644 samples/rest/payment/CreateFuturePayment.php delete mode 100755 samples/rest/payment/CreatePayment.php delete mode 100755 samples/rest/payment/CreatePaymentUsingPayPal.php delete mode 100755 samples/rest/payment/CreatePaymentUsingSavedCardVault.php delete mode 100644 samples/rest/payment/CreateThirdPartyPayment.php delete mode 100755 samples/rest/payment/ExecutePayment.php delete mode 100755 samples/rest/payment/GetAuthorization.php delete mode 100755 samples/rest/payment/GetCapture.php delete mode 100755 samples/rest/payment/ListPayments.php delete mode 100755 samples/rest/payment/OrderAuthorize.php delete mode 100755 samples/rest/payment/OrderCapture.php delete mode 100644 samples/rest/payment/OrderCreateForAuthorization.php delete mode 100644 samples/rest/payment/OrderCreateForCapture.php delete mode 100644 samples/rest/payment/OrderCreateForVoid.php delete mode 100755 samples/rest/payment/OrderDoVoid.php delete mode 100755 samples/rest/payment/OrderGet.php delete mode 100644 samples/rest/payment/Reauthorization.php delete mode 100755 samples/rest/payment/RefundCapture.php delete mode 100755 samples/rest/payment/ShowPaymentDetails.php delete mode 100644 samples/rest/payment/ShowRefundDetails.php delete mode 100644 samples/rest/payment/UpdatePayment.php delete mode 100755 samples/rest/payment/VoidAuthorization.php delete mode 100755 samples/rest/paymentexperience/CreateWebProfile.php delete mode 100755 samples/rest/paymentexperience/DeleteWebProfile.php delete mode 100755 samples/rest/paymentexperience/GetWebProfile.php delete mode 100755 samples/rest/paymentexperience/ListWebProfiles.php delete mode 100755 samples/rest/paymentexperience/PartiallyUpdateWebProfile.php delete mode 100755 samples/rest/paymentexperience/UpdateWebProfile.php delete mode 100755 samples/rest/payouts/CancelPayoutItem.php delete mode 100755 samples/rest/payouts/CreateBatchPayout.php delete mode 100755 samples/rest/payouts/CreateSinglePayout.php delete mode 100755 samples/rest/payouts/GetPayoutBatchStatus.php delete mode 100755 samples/rest/payouts/GetPayoutItemStatus.php delete mode 100644 samples/rest/paypal_sync/PaypalSyncTransactions.php delete mode 100644 samples/rest/referenced_payouts/CreateReferencedBatchPayout.php delete mode 100644 samples/rest/sale/GetSale.php delete mode 100644 samples/rest/sale/RefundSale.php delete mode 100755 samples/rest/vault/DeleteCreditCard.php delete mode 100644 samples/rest/vault/GetCardDetails.php delete mode 100755 samples/rest/vault/ListCreditCards.php delete mode 100644 samples/rest/vault/StoreCreditCard.php delete mode 100755 samples/rest/vault/UpdateCreditCard.php delete mode 100755 src/angelleye/PayPal/rest/billing/BillingAPI.php delete mode 100644 src/angelleye/PayPal/rest/checkout_orders/CheckoutOrdersAPI.php delete mode 100644 src/angelleye/PayPal/rest/customerdisputes/CustomerDisputesAPI.php delete mode 100644 src/angelleye/PayPal/rest/identity/IdentityAPI.php delete mode 100755 src/angelleye/PayPal/rest/invoice/InvoiceAPI.php delete mode 100644 src/angelleye/PayPal/rest/invoice/InvoiceAPIv2.php delete mode 100644 src/angelleye/PayPal/rest/notifications/NotificationsAPI.php delete mode 100755 src/angelleye/PayPal/rest/paymentexperience/PaymentExperianceAPI.php delete mode 100755 src/angelleye/PayPal/rest/payments/PaymentAPI.php delete mode 100755 src/angelleye/PayPal/rest/payouts/PayoutsAPI.php delete mode 100644 src/angelleye/PayPal/rest/paypal_sync/PayPalSyncAPI.php delete mode 100644 src/angelleye/PayPal/rest/referenced_payouts/ReferencedPayoutsAPI.php delete mode 100755 src/angelleye/PayPal/rest/vault/CreditCardAPI.php delete mode 100644 templates/rest/billing_agreements/BillAgreementBalance.php delete mode 100644 templates/rest/billing_agreements/CancelBillingAgreement.php delete mode 100644 templates/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php delete mode 100644 templates/rest/billing_agreements/CreateBillingAgreementWithPayPal.php delete mode 100644 templates/rest/billing_agreements/ExecuteAgreement.php delete mode 100644 templates/rest/billing_agreements/GetBillingAgreement.php delete mode 100644 templates/rest/billing_agreements/ReactivateBillingAgreement.php delete mode 100644 templates/rest/billing_agreements/SearchBillingTransactions.php delete mode 100644 templates/rest/billing_agreements/SetAgreementBalance.php delete mode 100644 templates/rest/billing_agreements/SuspendBillingAgreement.php delete mode 100644 templates/rest/billing_agreements/UpdateBillingAgreement.php delete mode 100644 templates/rest/billing_plans/CreatePlan.php delete mode 100644 templates/rest/billing_plans/DeletePlan.php delete mode 100644 templates/rest/billing_plans/GetPlan.php delete mode 100644 templates/rest/billing_plans/ListPlans.php delete mode 100644 templates/rest/billing_plans/UpdatePlan.php delete mode 100644 templates/rest/checkout_orders/AuthorizeOrder.php delete mode 100644 templates/rest/checkout_orders/CaptureAuthorizedPayment.php delete mode 100644 templates/rest/checkout_orders/CaptureOrder.php delete mode 100644 templates/rest/checkout_orders/CreateAuthorizeOrder.php delete mode 100644 templates/rest/checkout_orders/CreateCaptureOrder.php delete mode 100644 templates/rest/checkout_orders/GetAuthorizePaymentDetails.php delete mode 100644 templates/rest/checkout_orders/GetCapturedPaymentDetails.php delete mode 100644 templates/rest/checkout_orders/GetOrderDetails.php delete mode 100644 templates/rest/checkout_orders/Reauthorize.php delete mode 100644 templates/rest/checkout_orders/RefundCapturedPayment.php delete mode 100644 templates/rest/checkout_orders/ShowRefundDetails.php delete mode 100644 templates/rest/checkout_orders/VoidAuthorizedPayment.php delete mode 100644 templates/rest/customer-disputes/AcceptClaim.php delete mode 100644 templates/rest/customer-disputes/DisputesAppeal.php delete mode 100644 templates/rest/customer-disputes/DisputesEscalate.php delete mode 100644 templates/rest/customer-disputes/DisputesMakeOffer.php delete mode 100644 templates/rest/customer-disputes/ListDisputes.php delete mode 100644 templates/rest/customer-disputes/ProvideEvidence.php delete mode 100644 templates/rest/customer-disputes/SendMessageToOtherParty.php delete mode 100644 templates/rest/customer-disputes/SettleDispute.php delete mode 100644 templates/rest/customer-disputes/ShowDisputeDetails.php delete mode 100644 templates/rest/customer-disputes/UpdateDisputeStatus.php delete mode 100644 templates/rest/identity/GetUserConsentURL.php delete mode 100644 templates/rest/identity/GetUserInfo.php delete mode 100644 templates/rest/identity/UserConsentRedirect.php delete mode 100755 templates/rest/invoice-templates/CreateInvoiceTemplate.php delete mode 100755 templates/rest/invoice-templates/DeleteInvoiceTemplate.php delete mode 100755 templates/rest/invoice-templates/GetAllInvoiceTemplates.php delete mode 100755 templates/rest/invoice-templates/GetInvoiceTemplate.php delete mode 100755 templates/rest/invoice-templates/UpdateInvoiceTemplate.php delete mode 100755 templates/rest/invoice/CancelInvoice.php delete mode 100755 templates/rest/invoice/CreateInvoice.php delete mode 100644 templates/rest/invoice/CreateThirdPartyInvoice.php delete mode 100755 templates/rest/invoice/DeleteInvoice.php delete mode 100755 templates/rest/invoice/GetInvoice.php delete mode 100755 templates/rest/invoice/GetNextInvoiceNumber.php delete mode 100644 templates/rest/invoice/GetThirdPartyInvoice.php delete mode 100755 templates/rest/invoice/ListInvoice.php delete mode 100755 templates/rest/invoice/RecordPayment.php delete mode 100755 templates/rest/invoice/RecordRefund.php delete mode 100755 templates/rest/invoice/RemindInvoice.php delete mode 100755 templates/rest/invoice/RetrieveQRCode.php delete mode 100755 templates/rest/invoice/SearchInvoices.php delete mode 100755 templates/rest/invoice/SendInvoice.php delete mode 100755 templates/rest/invoice/UpdateInvoice.php delete mode 100644 templates/rest/notifications/CreateWebhook.php delete mode 100644 templates/rest/notifications/DeleteWebhook.php delete mode 100644 templates/rest/notifications/EventNotificationDetails.php delete mode 100644 templates/rest/notifications/GetWebhook.php delete mode 100644 templates/rest/notifications/ListEventSubscriptionsForWebhook.php delete mode 100644 templates/rest/notifications/ListWebhooks.php delete mode 100644 templates/rest/notifications/PayPal_Webhooks.txt delete mode 100644 templates/rest/notifications/ResendEventNotification.php delete mode 100644 templates/rest/notifications/SearchWebhookEvents.php delete mode 100644 templates/rest/notifications/SimulateEvent.php delete mode 100644 templates/rest/notifications/UpdateWebhook.php delete mode 100644 templates/rest/notifications/VerifyWebhookSignature.php delete mode 100644 templates/rest/notifications/WebhooksEventTypes.php delete mode 100755 templates/rest/payment/AuthorizationCapture.php delete mode 100755 templates/rest/payment/CreatePayment.php delete mode 100755 templates/rest/payment/CreatePaymentUsingPayPal.php delete mode 100755 templates/rest/payment/CreatePaymentUsingSavedCardVault.php delete mode 100644 templates/rest/payment/CreateThirdPartyPayment.php delete mode 100755 templates/rest/payment/ExecutePayment.php delete mode 100755 templates/rest/payment/GetAuthorization.php delete mode 100755 templates/rest/payment/GetCapture.php delete mode 100755 templates/rest/payment/ListPayments.php delete mode 100755 templates/rest/payment/OrderAuthorize.php delete mode 100755 templates/rest/payment/OrderCapture.php delete mode 100755 templates/rest/payment/OrderDoVoid.php delete mode 100755 templates/rest/payment/OrderGet.php delete mode 100644 templates/rest/payment/Reauthorization.php delete mode 100755 templates/rest/payment/RefundCapture.php delete mode 100755 templates/rest/payment/ShowPaymentDetails.php delete mode 100644 templates/rest/payment/ShowRefundDetails.php delete mode 100644 templates/rest/payment/UpdatePayment.php delete mode 100755 templates/rest/payment/VoidAuthorization.php delete mode 100755 templates/rest/paymentexperience/CreateWebProfile.php delete mode 100755 templates/rest/paymentexperience/DeleteWebProfile.php delete mode 100755 templates/rest/paymentexperience/GetWebProfile.php delete mode 100755 templates/rest/paymentexperience/ListWebProfiles.php delete mode 100755 templates/rest/paymentexperience/PartiallyUpdateWebProfile.php delete mode 100755 templates/rest/paymentexperience/UpdateWebProfile.php delete mode 100755 templates/rest/payouts/CancelPayoutItem.php delete mode 100755 templates/rest/payouts/CreateBatchPayout.php delete mode 100755 templates/rest/payouts/CreateSinglePayout.php delete mode 100755 templates/rest/payouts/GetPayoutBatchStatus.php delete mode 100755 templates/rest/payouts/GetPayoutItemStatus.php delete mode 100644 templates/rest/paypal_sync/paypal_sync_transactions.php delete mode 100644 templates/rest/referenced_payouts/create_referenced_batch_payout.php delete mode 100644 templates/rest/sale/GetSale.php delete mode 100644 templates/rest/sale/RefundSale.php delete mode 100755 templates/rest/vault/DeleteCreditCard.php delete mode 100644 templates/rest/vault/GetCardDetails.php delete mode 100755 templates/rest/vault/ListCreditCards.php delete mode 100644 templates/rest/vault/StoreCreditCard.php delete mode 100755 templates/rest/vault/UpdateCreditCard.php diff --git a/composer.json b/composer.json index c734bfda..ebbe460a 100755 --- a/composer.json +++ b/composer.json @@ -14,8 +14,7 @@ ], "require": { "php": ">=5.3.0", - "ext-curl": "*", - "paypal/rest-api-sdk-php":"*" + "ext-curl": "*" }, "autoload": { "psr-0": { diff --git a/demo/rest/rest-checkout-line-items-v1/CreatePaymentUsingPayPal.php b/demo/rest/rest-checkout-line-items-v1/CreatePaymentUsingPayPal.php deleted file mode 100644 index c0504fdf..00000000 --- a/demo/rest/rest-checkout-line-items-v1/CreatePaymentUsingPayPal.php +++ /dev/null @@ -1,96 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray); - -/** - * In this demo we are using Sale for the intent value. - * - * Possible values for intent include: - * - * sale - Immediate payment. - * authorize - Authorize a payment for future capture. - * order - Create an order for future capture, but without an authorization. - */ -$intent= $_SESSION['intent']; - -/** - * Here we are setting up the parameters for a basic Checkout flow. - * - * The template provided at /vendor/angelleye/paypal-php-library/templates/rest/payment/CreatePaymentUsingPayPal.php - * contains a lot more parameters that we aren't using here, so I've removed them to keep this clean. - * - * $domain used here is set in the config file. - */ - -$urls= array( - 'ReturnUrl' => 'GetPaymentDetails.php?success=true', // Required when Pay using paypal. Example : ExecutePayment.php?success=true - 'CancelUrl' => 'index.php?success=false', // Required when Pay using paypal. Example : ExecutePayment.php?success=false - 'BaseUrl' => $domain.'demo/rest/rest-checkout-line-items-v1/' // Required. The base url that we pass for the return. -); - -$invoiceNumber= $_SESSION['invoiceNumber']; -$NoteToPayer = $_SESSION['NoteToPayer']; -$orderItems = $_SESSION['items']; -$paymentDetails = $_SESSION['paymentDetails']; -$amount = $_SESSION['amount']; - -/** - * Now we gather all of the data above into a single array. - */ - -$requestData = array( - 'intent' => $intent, - 'invoiceNumber' => $invoiceNumber, - 'orderItems' => $orderItems, - 'paymentDetails' => $paymentDetails, - 'amount' => $amount, - 'urls' => $urls, - 'NoteToPayer' => $NoteToPayer -); - -/** - * Here we are making the call to the create_payment_with_paypal function in the library, - * and we're passing in our $requestData that we just set above. - */ - -$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData); - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If all goes well then redirect the user to PayPal - * using the approvalUrl returned by the create_payment_with_paypal() function. - */ - -if($returnArray['RESULT'] == 'Success'){ - $approvalUrl = $returnArray['PAYMENT']['approvalUrl']; - header('Location: ' . $approvalUrl); -} -else{ - /** - * Error page redirection - */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $returnArray; - header('Location: ../../error.php'); -} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v1/ExecutePayment.php b/demo/rest/rest-checkout-line-items-v1/ExecutePayment.php deleted file mode 100644 index efb24987..00000000 --- a/demo/rest/rest-checkout-line-items-v1/ExecutePayment.php +++ /dev/null @@ -1,51 +0,0 @@ -/execute'. - */ - - -/** - * Setup configuration for the PayPal library using vars from the config file. - * Then load the PayPal object into $PayPal - */ - -$configArray = array( - 'Sandbox' => $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray); - -$paymentId = $_SESSION['payment_id']; -$payer_id = $_SESSION['payer_info']['payer_id']; -$amount = $_SESSION['amount']; -$returnArray = $PayPal->ExecutePayment($paymentId,$payer_id,$amount); - -if($returnArray['RESULT'] == 'Success'){ - $_SESSION['Payment_transaction_id'] = $returnArray['PAYMENT']['transactions'][0]['related_resources'][0]['sale']['id']; - $_SESSION['RESULT'] = $returnArray; - header('Location: order-complete.php'); -} -else{ - /** - * Error page redirection - */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $returnArray; - header('Location: ../../error.php'); -} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v1/GetPaymentDetails.php b/demo/rest/rest-checkout-line-items-v1/GetPaymentDetails.php deleted file mode 100644 index 50d895e7..00000000 --- a/demo/rest/rest-checkout-line-items-v1/GetPaymentDetails.php +++ /dev/null @@ -1,131 +0,0 @@ -/execute'. - */ - - -/** - * Setup configuration for the PayPal library using vars from the config file. - * Then load the PayPal object into $PayPal - */ - -$configArray = array( - 'Sandbox' => $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray); - - -// ### Approval Status -// Determine if the user approved the payment or not -if (isset($_GET['success']) && $_GET['success'] == 'true') { - $paymentId = $_GET['paymentId']; - $payer_id = $_GET['PayerID']; - $_SESSION['payment_id'] = $paymentId; - - /** ### Optional Changes to Amount - If you wish to update the amount that you wish to charge the customer, - based on the shipping address or any other reason, you could - do that by passing the transaction object with just `amount` field in it. - Please run the example with $details object in samples\rest\payment\ExecutePayment.php in our library - */ - - $returnArray = $PayPal->ShowPaymentDetails($paymentId); - - if($returnArray['RESULT'] == 'Success'){ - - /** - * Get Payer info - * For demonstration purpose , we are just taking few parameters from the payer's object. - * You can get more data of the like payer like birth_date,tax_id,tax_id_type... - */ - - $payer_info = array(); - $payer_info['suffix'] = isset($returnArray['PAYMENT']['payer']['payer_info']['suffix']) ? $returnArray['PAYMENT']['payer']['payer_info']['suffix'] : ''; - $payer_info['first_name'] = isset($returnArray['PAYMENT']['payer']['payer_info']['first_name']) ? $returnArray['PAYMENT']['payer']['payer_info']['first_name'] : ''; - $payer_info['middle_name'] = isset($returnArray['PAYMENT']['payer']['payer_info']['middle_name']) ? $returnArray['PAYMENT']['payer']['payer_info']['middle_name'] : ''; - $payer_info['last_name'] = isset($returnArray['PAYMENT']['payer']['payer_info']['last_name']) ? $returnArray['PAYMENT']['payer']['payer_info']['last_name'] : ''; - $payer_info['payer_id'] = isset($returnArray['PAYMENT']['payer']['payer_info']['payer_id']) ? $returnArray['PAYMENT']['payer']['payer_info']['payer_id'] : ''; - $payer_info['email'] = isset($returnArray['PAYMENT']['payer']['payer_info']['email']) ? $returnArray['PAYMENT']['payer']['payer_info']['email'] : ''; - - /** - * Storing payer's object to the session to display them on next step. - */ - - $_SESSION['payer_info'] = $payer_info; - - /** - * Get Shipping info from the payment details and set to the session - */ - $shipping_address = array(); - $shipping_address['line1'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['line1']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['line1'] : ''; - $shipping_address['line2'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['line2']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['line2'] : ''; - $shipping_address['city'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['city']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['city'] : ''; - $shipping_address['state'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['state']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['state'] : ''; - $shipping_address['postal_code'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['postal_code']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['postal_code'] : ''; - $shipping_address['country_code'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['country_code']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['country_code'] : ''; - $shipping_address['phone'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['phone']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['phone'] : ''; - $shipping_address['type'] = isset($returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['type']) ? $returnArray['PAYMENT']['payer']['payer_info']['shipping_address']['type'] : ''; - - /** - * Storing shipping_address's object to the session to display them on next step. - */ - $_SESSION['shipping_address'] = $shipping_address; - - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - * - * We can do that by passing the transaction object with just `amount` field in it. - */ - - $_SESSION['paymentDetails'] = array( - 'Subtotal' => isset($_SESSION['amount']['Total']) ? number_format($_SESSION['amount']['Total'],2) : '', - 'Shipping' => '1.20', - 'Tax' => '1.30' - ); - - $total = $_SESSION['paymentDetails']['Shipping'] + $_SESSION['paymentDetails']['Tax'] + $_SESSION['paymentDetails']['Subtotal']; - - $amount = array( - 'Currency' => 'USD', - 'Total' => number_format($total,2), - 'Details' => $_SESSION['paymentDetails'] - ); - $_SESSION['amount'] = $amount; - - header('Location: review.php'); - } - else{ - /** - * Error page redirection - */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $returnArray; - header('Location: ../../error.php'); - } -} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v1/index.php b/demo/rest/rest-checkout-line-items-v1/index.php deleted file mode 100644 index d44da2e3..00000000 --- a/demo/rest/rest-checkout-line-items-v1/index.php +++ /dev/null @@ -1,190 +0,0 @@ - '123', // Stock keeping unit corresponding (SKU) to item. - 'Name' => 'Hat', // Item name. 127 characters max. - 'Description' => 'Kansas City Chiefs Large Multi-Fit Hat', // Description of the item. Only supported when the `payment_method` is set to `paypal`. - 'Quantity' => '1', // Number of a particular item. 10 characters max - 'Price' => '7.50', // Item cost. 10 characters max. - 'Currency' => $currency, // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). - 'Tax' => '' // Tax of the item. Only supported when the `payment_method` is set to `paypal`. -); - -$_SESSION['items'][1] = array( - 'Sku' => '678', // Stock keeping unit corresponding (SKU) to item. - 'Name' => 'Handbag', // Item name. 127 characters max. - 'Description' => 'Small, leather handbag.', // Description of the item. Only supported when the `payment_method` is set to `paypal`. - 'Quantity' => '2', // Number of a particular item. 10 characters max - 'Price' => '10.00', // Item cost. 10 characters max. - 'Currency' => $currency, // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). - 'Tax' => '' // Tax of the item. Only supported when the `payment_method` is set to `paypal`. -); - -$_SESSION['orderItems'] = $_SESSION['items']; - -$_SESSION['paymentDetails'] = array( - 'Subtotal' => '27.50', // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places. - 'Shipping' => '0.00', // Amount charged for shipping. 10 characters max with support for 2 decimal places. - 'Tax' => '0.00', // Amount charged for tax. 10 characters max with support for 2 decimal places. - 'GiftWrap' => '0.00' // Amount being charged as gift wrap fee. -); - -/** - * below code is for the grand total - */ -$_SESSION['amount']['Total'] = number_format($_SESSION['paymentDetails']['Subtotal'] + $_SESSION['paymentDetails']['Shipping'] + $_SESSION['paymentDetails']['Tax'] + $_SESSION['paymentDetails']['GiftWrap'],2); -$_SESSION['amount']['Currency'] = $currency; -?> - - - -Create and Execute Payment using PayPal w/ Line items | REST | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Shopping Cart

-

Here we are using a basic shopping cart for display purposes. -

- For this basic demo, all we are sending to PayPal is the payment details, order items, and order total. We are assuming that we have not collected any - billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal - after the user logs in and is returned back to the site.

-

To complete the demo, click the PayPal button and use the following credentials to login for payment.

- Email Address: paypal-buyer@angelleye.com
- Password: paypalphp -

-
-
-
- - - - - - - - - - - - - - - -
Intent
Invoice Number
Note To Payer
-
-
- - - - - - - - - - - - - - - - - - - - - - - -
SkuNameDescriptionPriceQTYTotal
$ $
-
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Tax$
Gift Wrap$
Grand Total$
-
-
-
-
-
- - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v1/order-complete.php b/demo/rest/rest-checkout-line-items-v1/order-complete.php deleted file mode 100644 index 251f555f..00000000 --- a/demo/rest/rest-checkout-line-items-v1/order-complete.php +++ /dev/null @@ -1,167 +0,0 @@ - - - - -Create and Execute Payment using PayPal w/ Line items | REST | Order Complete | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Payment Complete!

-

- We have now reached the final thank you / receipt page and the payment has been processed! -

- We have added the PayPal payment ID and transaction ID to the Billing Information section. -

-
-
- - - - - - - - - - - - - - - -
Intent
Invoice Number
Note To Payer
-
-
- - - - - - - - - - - - - - - - - - - - - - - -
SkuNameDescriptionPriceQTYTotal
$ $
-
-
-

Billing Information

-

- Payer ID : '.$_SESSION['payer_info']['payer_id'] : ''; - echo (!empty($_SESSION['payment_id'])) ? '
Payment ID : '. $_SESSION['payment_id'] : ''; - echo (!empty($_SESSION['payment_id'])) ? '
Transaction ID : '. $_SESSION['Payment_transaction_id'] : ''; - ?> -

-
-
-

Shipping Information

-

- '.$_SESSION['shipping_address']['line2'] : ''; - echo (!empty($_SESSION['shipping_address']['city'])) ? '
'.$_SESSION['shipping_address']['city'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['state'])) ? $_SESSION['shipping_address']['state'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['postal_code'])) ? $_SESSION['shipping_address']['postal_code'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['country_code'])) ? $_SESSION['shipping_address']['country_code'] : ''; - echo (!empty($_SESSION['shipping_address']['phone'])) ? '
'.$_SESSION['shipping_address']['phone'] : ''; - echo (!empty($_SESSION['shipping_address']['type'])) ? '
Address Type : '.$_SESSION['shipping_address']['type'] : ''; - ?> -

-
-
- - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Tax$
Gift Wrap$
Grand Total$
-
-
-
-
-
- - - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v1/review.php b/demo/rest/rest-checkout-line-items-v1/review.php deleted file mode 100644 index 5fb5adf6..00000000 --- a/demo/rest/rest-checkout-line-items-v1/review.php +++ /dev/null @@ -1,147 +0,0 @@ - - - - -Create and Execute Payment using PayPal w/ Line items | REST | Order Review | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Order Review

-

Here we display a final review to the buyer now that we've calculated shipping, handling, tax and other charges. The - billing and shipping information provided here is what we obtained by calling the GetPaymentDetails API. -

-

- The payment has not been processed at this point because we have not yet called the final ExecutePayment API. This will - happen when we click the "Complete Order" button below. -

- - - - - - - - - - - - - - - - - - - - - - - -
SkuNameDescriptionPriceQTYTotal
$ $
-
-
-

Billing Information

-

- Payer ID : '.$_SESSION['payer_info']['payer_id'] : ''; - echo (!empty($_SESSION['payment_id'])) ? '
Payment ID : '. $_SESSION['payment_id'] : ''; - ?> -

-
-
-

Shipping Information

-

- '.$_SESSION['shipping_address']['line2'] : ''; - echo (!empty($_SESSION['shipping_address']['city'])) ? '
'.$_SESSION['shipping_address']['city'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['state'])) ? $_SESSION['shipping_address']['state'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['postal_code'])) ? $_SESSION['shipping_address']['postal_code'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['country_code'])) ? $_SESSION['shipping_address']['country_code'] : ''; - echo (!empty($_SESSION['shipping_address']['phone'])) ? '
'.$_SESSION['shipping_address']['phone'] : ''; - echo (!empty($_SESSION['shipping_address']['type'])) ? '
Address Type : '.$_SESSION['shipping_address']['type'] : ''; - ?> -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Tax$
Gift Wrap$
Grand Total$
Complete Order
-
-
-
-
-
- - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/CaptureOrder.php b/demo/rest/rest-checkout-line-items-v2/CaptureOrder.php deleted file mode 100644 index c19a9806..00000000 --- a/demo/rest/rest-checkout-line-items-v2/CaptureOrder.php +++ /dev/null @@ -1,40 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new CheckoutOrdersAPI($configArray); - -$order_id = $_SESSION['checkout_order_id']; // The ID of the order for which to capture a payment. -$response = $PayPal->CaptureOrder($order_id); -/** - * Check if the response is successful then pass the order object and transaction id otherwise send appropriate error message. - */ -if($response['RESULT'] == 'Success'){ - $_SESSION['order_transaction_id'] = isset($response['TRANSACTION_ID']) ? $response['TRANSACTION_ID'] : ''; - header('Location: order-complete.php'); -} -else{ - /** Error page redirection */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $response; - header('Location: ../../error.php'); -} -exit; \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/CreateCaptureOrder.php b/demo/rest/rest-checkout-line-items-v2/CreateCaptureOrder.php deleted file mode 100644 index 580a2536..00000000 --- a/demo/rest/rest-checkout-line-items-v2/CreateCaptureOrder.php +++ /dev/null @@ -1,122 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new CheckoutOrdersAPI($configArray); - -/** - * Here we are setting up the parameters for a basic Checkout flow. - * - * The template provided at /vendor/angelleye/paypal-php-library/templates/rest/checkout_orders/CreateCaptureOrder.php - * contains a lot more parameters that we aren't using here, so I've removed them to keep this clean. - */ - -/** - * Get data that are previously stored in session and create an order request. - */ -$intent = 'CAPTURE'; -$currency = $_SESSION['currency']; -$orderItems = $_SESSION['orderItems']; - -$amount = array( - 'currency_code' => $currency, - 'value' => $_SESSION['amount']['Total'], - 'breakdown' => array( - 'item_total' => array( // The subtotal for all items. - 'value' => $_SESSION['paymentDetails']['item_total'], - 'currency_code' => $currency - ), - 'shipping' => array( // The shipping fee for all items. - 'value' => $_SESSION['paymentDetails']['shipping'], - 'currency_code' => $currency - ), - 'handling' => array( // The handling fee for all items. - 'value' => $_SESSION['paymentDetails']['handling'], - 'currency_code' => $currency - ), - 'tax_total' => array( // The total tax for all items. - 'value' =>$_SESSION['paymentDetails']['tax_total'], - 'currency_code' => $currency - ), - 'insurance' => array( // The insurance fee for all items. - 'value' =>$_SESSION['paymentDetails']['insurance'], - 'currency_code' => $currency - ), - 'shipping_discount' => array( // The shipping discount for all items. - 'value' =>$_SESSION['paymentDetails']['shipping_discount'], - 'currency_code' => $currency - ) - ) -); - -$application_context = array( - 'brand_name' => 'AngellEye INC', // The label that overrides the business name in the PayPal account on the PayPal site. - 'locale' => 'en-US', // PayPal supports a five-character code. - 'landing_page' => 'LOGIN', // Allowed Values : LOGIN,BILLING - 'shipping_preferences' => 'GET_FROM_FILE', // Allowed Values : GET_FROM_FILE , NO_SHIPPING , SET_PROVIDED_ADDRESS - 'user_action' => 'CONTINUE', // Configures a Continue or Pay Now checkout flow. - 'payment_method' => array( - 'payer_selected' => 'PAYPAL', // Values : PAYPAL,PAYPAL_CREDIT. The customer and merchant payment preferences. - 'payee_preferred' => 'UNRESTRICTED' // Values : UNRESTRICTED , IMMEDIATE_PAYMENT_REQUIRED - ), - 'cancel_url' => $domain.'demo/rest/rest-checkout-line-items-v2/index.php?success=false', - 'return_url' => $domain.'demo/rest/rest-checkout-line-items-v2/GetOrderDetails.php?success=true' -); - -$purchase_units = array( - 'reference_id' => 'default', // The ID for the purchase unit. Required for multiple purchase_units or if an order must be updated by using PATCH. If you omit the reference_id for an order with one purchase unit, PayPal sets the reference_id to default. - 'description' => 'Leather Goods', // The purchase description. Maximum length: 127. - 'custom_id' => 'CUST-PayPalFashions', // The API caller-provided external ID. Used to reconcile client transactions with PayPal transactions. Appears in transaction and settlement reports but is not visible to the payer. - 'soft_descriptor' => 'PayPalFashions', // The payment descriptor on the payer's credit card statement. Maximum length: 22. - 'invoice_id' => 'AEINV-'.rand(0,1000), // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. Maximum length: 127. - 'amount' => $amount, - 'items' => $orderItems -); - -/** - * Now we gather all of the data above into a single array. - */ - -$requestArray = array( - 'intent'=>$intent, - 'application_context' => $application_context, - 'purchase_units' => $purchase_units, -); - -/** - * Here we are making the call to the CreateOrder function in the library, - * and we're passing in our $requestArray that we just set above. - */ - -$response = $PayPal->CreateOrder($requestArray); - -if($response['RESULT'] == 'Success'){ - $_SESSION['checkout_order_id'] = isset($response['ORDER']['id']) ? $response['ORDER']['id'] : ''; - header('Location: ' . $response['APPROVAL_LINK']); -} -else{ - /** - * Error page redirection - */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $response; - header('Location: ../../error.php'); -} -exit; \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/GetOrderDetails.php b/demo/rest/rest-checkout-line-items-v2/GetOrderDetails.php deleted file mode 100644 index 768069d4..00000000 --- a/demo/rest/rest-checkout-line-items-v2/GetOrderDetails.php +++ /dev/null @@ -1,148 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new CheckoutOrdersAPI($configArray); - -if (isset($_GET['success']) && $_GET['success'] == 'true') { - $order_id = $_SESSION['checkout_order_id']; // The ID of the order for which to show details. - $response = $PayPal->GetOrderDetails($order_id); - - if($response['RESULT'] == 'Success'){ - /** - * Get Payer info - * For demonstration purpose , we are just taking few parameters from the payer's object. - */ - - $payer_info = array(); - $payer_info['first_name'] = isset($response['ORDER']['payer']['name']['given_name']) ? $response['ORDER']['payer']['name']['given_name'] : ''; - $payer_info['last_name'] = isset($response['ORDER']['payer']['name']['surname']) ? $response['ORDER']['payer']['name']['surname'] : ''; - $payer_info['email_address'] = isset($response['ORDER']['payer']['email_address']) ? $response['ORDER']['payer']['email_address'] : ''; - $payer_info['payer_id'] = isset($response['ORDER']['payer']['payer_id']) ? $response['ORDER']['payer']['payer_id'] : ''; - - /** - * Storing payer's object to the session to display them on next step. - */ - - $_SESSION['payer_info'] = $payer_info; - - /** - * Get Shipping info from the payment details and set to the session - */ - $shipping_address = array(); - $shipping_address['address_line_1'] = isset($response['ORDER']['purchase_units'][0]['shipping']['address']['address_line_1']) ? $response['ORDER']['purchase_units'][0]['shipping']['address']['address_line_1'] : ''; - $shipping_address['admin_area_2'] = isset($response['ORDER']['purchase_units'][0]['shipping']['address']['admin_area_2']) ? $response['ORDER']['purchase_units'][0]['shipping']['address']['admin_area_2'] : ''; - $shipping_address['admin_area_1'] = isset($response['ORDER']['purchase_units'][0]['shipping']['address']['admin_area_1']) ? $response['ORDER']['purchase_units'][0]['shipping']['address']['admin_area_1'] : ''; - $shipping_address['postal_code'] = isset($response['ORDER']['purchase_units'][0]['shipping']['address']['postal_code']) ? $response['ORDER']['purchase_units'][0]['shipping']['address']['postal_code'] : ''; - $shipping_address['country_code'] =isset($response['ORDER']['purchase_units'][0]['shipping']['address']['country_code']) ? $response['ORDER']['purchase_units'][0]['shipping']['address']['country_code'] : ''; - /** - * Storing shipping_address's object to the session to display them on next step. - */ - $_SESSION['shipping_address'] = $shipping_address; - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - * - * We can do that by updating order information using UpdateOrder API. - */ - - $Shipping = 1.20; - $Tax = 1.30; - $subtotal = isset($response['ORDER']['purchase_units'][0]['amount']['value']) ? $response['ORDER']['purchase_units'][0]['amount']['value'] : ''; - $total = $subtotal+$Shipping+$Tax; - - /** - * Updating our session variables - */ - $_SESSION['amount']['Total'] =$total; - $_SESSION['paymentDetails'] = array( - 'item_total' => $subtotal, - 'shipping' => $Shipping, - 'tax_total' =>$Tax, - 'handling' => 0.00, - 'insurance' => 0.00, - 'shipping_discount' => 0.00 - ); - - /** - * Calling UpdateOrder API. - */ - $patch_array = array( // Patch Request array. Read all Patch @ https://developer.paypal.com/docs/api/orders/v2/#orders_patch - 0 => - array( - "op" => "replace", - "path" => "/purchase_units/@reference_id=='default'/amount", - "value" => array( - 'currency_code' => 'USD', - 'value' => $total, - 'breakdown' => array( - 'item_total' => array( - 'value' => $subtotal, - 'currency_code' => $_SESSION['currency'], - ), - 'shipping' => array( - 'value' => $Shipping, - 'currency_code' => $_SESSION['currency'], - ), - 'tax_total' => array( - 'value' => $Tax, - 'currency_code' => $_SESSION['currency'], - ) - ) - ) - ) - ); - - $returnArray = $PayPal->UpdateOrder($order_id,$patch_array); - if($returnArray['RESULT'] == 'Success'){ - // put everything in session - header('Location: review.php'); - } - else{ - /** - * Error page redirection - */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $returnArray; - header('Location: ../../error.php'); - } - } - else{ - /** - * Error page redirection - */ - $_SESSION['rest_errors'] = true; - $_SESSION['errors'] = $response; - header('Location: ../../error.php'); - } - echo "
";
-    print_r($response);
-    exit;
-}
-else{
-    echo "Payment got cancelled.";
-    exit;
-}
\ No newline at end of file
diff --git a/demo/rest/rest-checkout-line-items-v2/index.php b/demo/rest/rest-checkout-line-items-v2/index.php
deleted file mode 100644
index a85d67ba..00000000
--- a/demo/rest/rest-checkout-line-items-v2/index.php
+++ /dev/null
@@ -1,217 +0,0 @@
- '123',                                    // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => 'Hat',                                    // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => 'Kansas City Chiefs Large Multi-Fit Hat', // The detailed item description. Maximum length: 127.
-    'quantity'    => 1,                                        // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(
-        'value' => 7.50,
-        'currency_code' => $_SESSION['currency']
-    ),                                     // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-    'tax'         => array(
-        'value' => 0.00,
-        'currency_code' => $_SESSION['currency']
-    ),                                     // The item tax for each unit.
-    'category'    => 'PHYSICAL_GOODS'                          // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$items[1] = array(
-    'sku'         => '678',                                 // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => 'Handbag',                             // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => 'Small, leather handbag.',             // The detailed item description. Maximum length: 127.
-    'quantity'    => 2,                                     // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(
-        'value' => 5.00,
-        'currency_code' => $_SESSION['currency']
-    ),                                  // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-    'tax'         => array(
-        'value' => 0.00,
-        'currency_code' => $_SESSION['currency']
-    ),                                  // The item tax for each unit.
-    'category'    => 'PHYSICAL_GOODS'                       // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-
-$orderItems = $items;
-
-$_SESSION['orderItems'] = $orderItems;
-
-$paymentDetails = array(
-    'item_total' => 17.50,
-    'shipping' => 0.00,
-    'tax_total' => 0.00,
-    'handling' => 0.00,
-    'insurance' => 0.00,
-    'shipping_discount' => 0.00
-);
-$_SESSION['paymentDetails'] = $paymentDetails;
-
-/**
- * below code is for the grand total
- */
-$amount['Total'] = number_format($paymentDetails['item_total'] + $paymentDetails['shipping'] + $paymentDetails['tax_total'] + $paymentDetails['handling'] + $paymentDetails['insurance'] + $paymentDetails['shipping_discount'] ,2);
-$_SESSION['amount']['Total'] = $amount['Total'];
-?>
-
-
-    
-    PayPal Checkout JS SDK | Smart Button | PHP Class Library | Angell EYE
-    
-    
-    
-    
-
-    
-    
-    
-    
-
-    
-    
-
-    
-    
-
-    
-    
-    
-    
-    
-    
-    
-    
-    
-
-
-
-
-
-
- -

Shopping Cart

-

- Here we are using a basic shopping cart for display purposes, - and we are implementing the Orders API v2. - In this example we have Order intent set to Capture, which will process the payment immediately. -

-

To complete the demo, click the PayPal button and use the following credentials to login to PayPal.

- Email Address: paypal-buyer@angelleye.com
- Password: paypalphp -

-
- - - - - - - - - - - - - - - - - - - - - - - - -
SkuNameDescriptionPriceQTYTotal
$ $
-
-
- -
-
- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Tax$
Handling fee$
Insurance$
Shipping Discount$
Grand Total$
- -
-
-
-
-
-
- - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/order-complete.php b/demo/rest/rest-checkout-line-items-v2/order-complete.php deleted file mode 100644 index 4031d4dc..00000000 --- a/demo/rest/rest-checkout-line-items-v2/order-complete.php +++ /dev/null @@ -1,152 +0,0 @@ - - - - - Create and Execute Payment using PayPal w/ Line items | REST | Order Review | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Order Review

-

- We have now reached the final thank you / receipt page and the payment has been captured! -

We have added the PayPal Order ID and Transaction ID - to the Billing Information, which was provided in the CaptureOrder response. -

- - - - - - - - - - - - - - - - - - - - - - - -
SkuNameDescriptionPriceQTYTotal
$ $
-
-
-

Billing Information

-

- Payer ID : '.$_SESSION['payer_info']['payer_id'] : ''; - echo (!empty($_SESSION['payer_info']['email_address'])) ? '
Email ID : '.$_SESSION['payer_info']['email_address'] : ''; - echo (!empty($_SESSION['checkout_order_id'])) ? '
PayPal Order ID : '. $_SESSION['checkout_order_id'] : ''; - echo (!empty($_SESSION['order_transaction_id'])) ? '
Transaction ID : '. $_SESSION['order_transaction_id'] : ''; - ?> -

-
-
-

Shipping Information

-

- '.$_SESSION['shipping_address']['admin_area_2'] : ''; - echo (!empty($_SESSION['shipping_address']['admin_area_1'])) ? '
'.$_SESSION['shipping_address']['admin_area_1'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['postal_code'])) ? '
'.$_SESSION['shipping_address']['postal_code'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['country_code'])) ? $_SESSION['shipping_address']['country_code'] : ''; - ?> -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Tax$
Handling fee$
Insurance$
Shipping Discount$
Grand Total$
-
-
-
-
-
- - - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/review.php b/demo/rest/rest-checkout-line-items-v2/review.php deleted file mode 100644 index 4ae12107..00000000 --- a/demo/rest/rest-checkout-line-items-v2/review.php +++ /dev/null @@ -1,152 +0,0 @@ - - - - -Create and Execute Payment using PayPal w/ Line items | REST | Order Review | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Order Review

-

- Here we display a final confirmation to the buyer now that we've calculated shipping, handling, and tax. The - billing and shipping information provided here is what we obtained in the GetOrderDetails response. -

- The payment has not been processed at this point because we have not yet captured the Payment. That is what will - happen when we click the "Complete Order" button below. -

- - - - - - - - - - - - - - - - - - - - - - - -
SkuNameDescriptionPriceQTYTotal
$ $
-
-
-

Billing Information

-

- Payer ID : '.$_SESSION['payer_info']['payer_id'] : ''; - echo (!empty($_SESSION['payer_info']['email_address'])) ? '
Email ID : '.$_SESSION['payer_info']['email_address'] : ''; - echo (!empty($_SESSION['checkout_order_id'])) ? '
PayPal Order ID : '. $_SESSION['checkout_order_id'] : ''; - ?> -

-
-
-

Shipping Information

-

- '.$_SESSION['shipping_address']['admin_area_2'] : ''; - echo (!empty($_SESSION['shipping_address']['admin_area_1'])) ? '
'.$_SESSION['shipping_address']['admin_area_1'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['postal_code'])) ? '
'.$_SESSION['shipping_address']['postal_code'].', ' : ''; - echo (!empty($_SESSION['shipping_address']['country_code'])) ? $_SESSION['shipping_address']['country_code'] : ''; - ?> -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Tax$
Handling fee$
Insurance$
Shipping Discount$
Grand Total$
Complete Order
-
-
-
-
-
- - \ No newline at end of file diff --git a/samples/rest/billing_agreements/BillAgreementBalance.php b/samples/rest/billing_agreements/BillAgreementBalance.php deleted file mode 100644 index d8fdb327..00000000 --- a/samples/rest/billing_agreements/BillAgreementBalance.php +++ /dev/null @@ -1,24 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray); - -$agreementId = 'I-C76T8XF96HBX'; // The ID of the agreement for which to bill the balance. -$note = 'Billing balance amount.'; // The reason for the agreement state change. - -$returnArray = $PayPal->BillAgreementBalance($agreementId,$note); - -echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/CancelBillingAgreement.php b/samples/rest/billing_agreements/CancelBillingAgreement.php
deleted file mode 100644
index a58c1383..00000000
--- a/samples/rest/billing_agreements/CancelBillingAgreement.php
+++ /dev/null
@@ -1,24 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = 'I-C76T8XF96HBX';                       // Required. The ID of the Billing Agreement for which to Suspend Billing Agreement.
-$note        = 'Canceling the agreement.';             // Required. Reason for changing the state of the agreement. 
-
-$returnArray = $PayPal->CancelBillingAgreement($agreementId,$note);
-
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php b/samples/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php
deleted file mode 100644
index c60a1c20..00000000
--- a/samples/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php
+++ /dev/null
@@ -1,74 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level    
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = 'P-4EM72741GL399293LUM5YCII';                     // Required. Billing plan id that will be used to create a billing agreement.
-
-$agreement = array(
-    "State" => '',                                          // State of the agreement.
-    "Name" => 'DPRP',                                       // Required. Name of the agreement.
-    "Description" => 'Payment with credit Card',            // Required. Description of the agreement.
-    "StartDate" => '2019-06-17T9:45:04Z'                    // Required. Start date of the agreement. Date format yyyy-MM-dd z, as defined in [ISO8601](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-
-$creditCard = array(
-    'Type' => 'visa',                                       // Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-    'Number' => '4111111111111111',                         // Required.  Credit card number.  No spaces or punctuation.  
-    'ExpireMonth' => '11',                                  // Required.  Credit card expiration Month.  Format is MM
-    'ExpireYear' => '2019',                                 // Required.  Credit card expiration year.  Format is YYYY
-    'Cvv2' => '012',                                        // Requirements determined by your PayPal account settings.  Security digits for credit card.                                     
-    'FirstName' => '',                                      // Cardholder's first name.
-    'LastName' => '',                                       // Cardholder's last name.  
-    'ExternalCustomerId' => '',                             // A unique identifier of the customer to whom this bank account belongs. Generated and provided by the facilitator. **This is now used in favor of `payer_id` when creating or using a stored funding instrument in the vault.
-    'MerchantId' => '',                                     // A user provided, optional convenvience field that functions as a unique identifier for the merchant on behalf of whom this credit card is being stored for. Note that this has no relation to PayPal merchant id  
-    'PayerId' => '',                                        // A unique identifier that you can assign and track when storing a credit card or using a stored credit card. This ID can help to avoid unintentional use or misuse of credit cards. This ID can be any value you would like to associate with the saved card, such as a UUID, username, or email address. Required when using a stored credit card if a payer_id was originally provided when storing the credit card in vault.
-    'ExternalCardId' => '',                                 // A unique identifier of the bank account resource. Generated and provided by the facilitator so it can be used to restrict the usage of the bank account to the specific merchant.        
-);
-
-$payer =array(
-    "PaymentMethod" => 'credit_card',                         // Required. Valid Values: ["credit_card", "bank", "paypal", "pay_upon_invoice", "carrier", "alternate_payment"]. Payment method being used - PayPal Wallet payment, Bank Direct Debit  or Direct Credit card.
-    "AccountType" => ''                                       // Valid Values: ["BUSINESS", "PERSONAL", "PREMIER"]. Type of account relationship payer has with PayPal. 
-);
-
-// Payerinfo is Required. 
-$payerInfo = array(
-    'email' => 'payer@domain.com',                           // Email address representing the payer. 127 characters max.
-    "first_name" => '',                                      // First name of the payer.
-    "last_name" => '',                                       // Last name of the payer.
-);
-
-$shippingAddress = array(
-    "Line1" => '111 First Street',                                          // Line 1 of the Address (eg. number, street, etc).
-    "Line2" => '',                                          // Optional line 2 of the Address (eg. suite, apt #, etc.). 
-    "City"  => 'Saratoga',                                          // City name.
-    "CountryCode" => 'US',                                    // 2 letter country code.
-    "PostalCode" => '95070',                                     // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-    "State" => 'CA',                                          // 2 letter code for US states, and the equivalent for other countries.
-    "NormalizationStatus" => ''                             // Valid Values: ["UNKNOWN", "UNNORMALIZED_USER_PREFERRED", "NORMALIZED", "UNNORMALIZED"]. Address normalization status    
-);
-
-$requestData = array(
-        "planId"          => $planId,
-        "agreement"       => $agreement,
-        "creditCard"      => $creditCard,
-        "payer"           => $payer,
-        "payerInfo"       => $payerInfo,
-        "shippingAddress" => $shippingAddress        
-);
-
-$returnArray = $PayPal->CreateBillingAgreement($requestData);
-
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/CreateBillingAgreementWithPayPal.php b/samples/rest/billing_agreements/CreateBillingAgreementWithPayPal.php
deleted file mode 100644
index 133203ce..00000000
--- a/samples/rest/billing_agreements/CreateBillingAgreementWithPayPal.php
+++ /dev/null
@@ -1,51 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level    
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = 'P-4EM72741GL399293LUM5YCII';                     // Required. Billing plan id that will be used to create a billing agreement.
-
-$agreement = array(
-    "State" => '',                                          // State of the agreement.
-    "Name" => 'DPRP',                                       // Required. Name of the agreement.
-    "Description" => 'Payment with Paypal',                 // Required. Description of the agreement.
-    "StartDate" => '2019-06-17T9:45:04Z'                    // Required. Start date of the agreement. Date format yyyy-MM-dd z, as defined in [ISO8601](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-
-// Payerinfo is Required.
-$payer =array(
-    "PaymentMethod" => 'paypal',                         // Required. Valid Values: ["credit_card", "bank", "paypal", "pay_upon_invoice", "carrier", "alternate_payment"]. Payment method being used - PayPal Wallet payment, Bank Direct Debit  or Direct Credit card.
-    "AccountType" => ''                                  // Valid Values: ["BUSINESS", "PERSONAL", "PREMIER"]. Type of account relationship payer has with PayPal. 
-);
-
-$shippingAddress = array(
-    "Line1" => '111 First Street',                              // Line 1 of the Address (eg. number, street, etc).
-    "Line2" => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.). 
-    "City"  => 'Saratoga',                                      // City name.
-    "CountryCode" => 'US',                                      // 2 letter country code.
-    "PostalCode" => '95070',                                    // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-    "State" => 'CA',                                            // 2 letter code for US states, and the equivalent for other countries.
-    "NormalizationStatus" => ''                                 // Valid Values: ["UNKNOWN", "UNNORMALIZED_USER_PREFERRED", "NORMALIZED", "UNNORMALIZED"]. Address normalization status    
-);
-
-$requestData = array(
-    "planId"          => $planId,
-    "agreement"       => $agreement,
-    "payer"           => $payer,
-    "shippingAddress" => $shippingAddress
-);
-
-$returnArray = $PayPal->CreateBillingAgreement($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/ExecuteAgreement.php b/samples/rest/billing_agreements/ExecuteAgreement.php
deleted file mode 100644
index 00a52836..00000000
--- a/samples/rest/billing_agreements/ExecuteAgreement.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-    $token = isset($_GET['token']) ? $_GET['token'] : '';
-    $result = $PayPal->ExecuteAgreement($token);
-    echo "
";
-    print_r($result);
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
\ No newline at end of file
diff --git a/samples/rest/billing_agreements/GetBillingAgreement.php b/samples/rest/billing_agreements/GetBillingAgreement.php
deleted file mode 100644
index 642426e7..00000000
--- a/samples/rest/billing_agreements/GetBillingAgreement.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = 'I-4U6DTW95XNLS';                       // Required. The ID of the Billing Agreement for which to show details.
-
-$returnArray = $PayPal->GetBillingAgreement($agreementId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/ReactivateBillingAgreement.php b/samples/rest/billing_agreements/ReactivateBillingAgreement.php
deleted file mode 100644
index f66af8a2..00000000
--- a/samples/rest/billing_agreements/ReactivateBillingAgreement.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = 'I-4U6DTW95XNLS';                       // Required. The ID of the Billing Agreement for which to Suspend Billing Agreement.
-$note        = 'Reactivating the agreement';           // Required. Reason for changing the state of the agreement. 
-
-$returnArray = $PayPal->ReactivateBillingAgreement($agreementId,$note);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/SearchBillingTransactions.php b/samples/rest/billing_agreements/SearchBillingTransactions.php
deleted file mode 100644
index b51274e2..00000000
--- a/samples/rest/billing_agreements/SearchBillingTransactions.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = 'I-4U6DTW95XNLS';                                // Identifier of the agreement resource for which to list transactions.
-/*Required*/
-$params = array(
-                'start_date' => '2019-01-01',                    // Format : yyyy-mm-dd . The start date of the range of transactions to list.
-                'end_date'   => '2019-12-31'                     // Format : yyyy-mm-dd . The end date of the range of transactions to list.
-          );
-
-$returnArray = $PayPal->SearchBillingTransactions($agreementId,$params);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/SetAgreementBalance.php b/samples/rest/billing_agreements/SetAgreementBalance.php
deleted file mode 100644
index 1215e0a5..00000000
--- a/samples/rest/billing_agreements/SetAgreementBalance.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = 'I-4U6DTW95XNLS';  // The ID of the agreement for which to set a balance.
-
-$amount = array(
-    'Currency' => 'USD',
-    'value' => '5.00'
-);
-
-$returnArray = $PayPal->SetAgreementBalance($agreementId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/SuspendBillingAgreement.php b/samples/rest/billing_agreements/SuspendBillingAgreement.php
deleted file mode 100644
index ae19dc8e..00000000
--- a/samples/rest/billing_agreements/SuspendBillingAgreement.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = 'I-4U6DTW95XNLS';                       // Required. The ID of the Billing Agreement for which to Suspend Billing Agreement.
-$note        = 'Suspending the agreement';             // Required. Reason for changing the state of the agreement. 
-
-$returnArray = $PayPal->SuspendBillingAgreement($agreementId,$note);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_agreements/UpdateBillingAgreement.php b/samples/rest/billing_agreements/UpdateBillingAgreement.php
deleted file mode 100644
index c96be4ed..00000000
--- a/samples/rest/billing_agreements/UpdateBillingAgreement.php
+++ /dev/null
@@ -1,32 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreement_id  = 'I-4U6DTW95XNLS';                                  // Required. Identifier of the agreement resource to update.
-
-$agreement = array(
-    "description" => 'Payment with Paypal',                 // Description of the agreement.   
-    "shipping_address" => array(
-        "line1" => '111 First Street',                              // Line 1 of the Address (eg. number, street, etc).
-        "line2" => '112 Second Street',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.). 
-        "city"  => 'Saratoga',                                      // City name.
-        "country_code" => 'US',                                      // 2 letter country code.
-        "postal_code" => '95070',                                    // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-        "state" => 'CA',                                            // 2 letter code for US states, and the equivalent for other countries.        
-    )
-);
-
-$returnArray = $PayPal->UpdateBillingAgreement($agreement_id,$agreement);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_plans/CreatePlan.php b/samples/rest/billing_plans/CreatePlan.php
deleted file mode 100644
index 3e8a9d05..00000000
--- a/samples/rest/billing_plans/CreatePlan.php
+++ /dev/null
@@ -1,110 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$plan = array(
-    'Name' => 'T-Shirt of the Month Club Plan',      // Required. Name of the billing plan. 128 characters max.
-    'Description' => 'Template creation.',           // Required. Description of the billing plan. 128 characters max.
-    'Type' => 'FIXED',                               // Required.  Type of the billing plan. Allowed values: `FIXED`, `INFINITE`.
-    'CreateTime' => '',                              // Time when the billing plan was created. Format YYYY-MM-DDTimeTimezone, as defined in [ISO8601](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-
-// Payment Definition is Required for creating Plan.
-$paymentDefinitions[0] = array(
-    'Name' => 'Regular Payments',             // Name of the payment definition. 128 characters max.
-    'Type' => 'REGULAR',                      // Allowed values: `TRIAL`, `REGULAR`. Type of the payment definition.
-    'FrequencyInterval' => '2',               // How frequently the customer should be charged.
-    'Frequency' => 'MONTH',                   // Allowed values: `WEEK`, `DAY`, `YEAR`, `MONTH`. Frequency of the payment definition offered.
-    'Cycles' => '12',                         // Number of cycles in this payment definition.
-    'Amount' => array(
-        'value' => 100.00,                    // Amount that will be charged at the end of each cycle for this payment definition.
-        'currency' => 'USD'                   // Three Letter Currency code.
-    ),
-    'ChargeModels' => array(
-        0 => array(
-            'Type' => 'SHIPPING',              // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => 10.00,              // Amount to charge.
-                'currency' => 'USD'            // Three Letter Currency code.
-            )
-        ),
-        1 => array(
-            'Type' => 'TAX',                   // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => 2.00,               // Amount to charge.
-                'currency' => 'USD'            // Three Letter Currency code.
-            )
-        )
-    )
-);
-
-$paymentDefinitions[1] = array(
-    'Name' => 'Trial payment definition',      // Name of the payment definition. 128 characters max.
-    'Type' => 'TRIAL',                         // Allowed values: `TRIAL`, `REGULAR`. Type of the payment definition.
-    'FrequencyInterval' => '5',                // How frequently the customer should be charged.
-    'Frequency' => 'WEEK',                     // Allowed values: `WEEK`, `DAY`, `YEAR`, `MONTH`. Frequency of the payment definition offered.
-    'Cycles' => '2',                           // Number of cycles in this payment definition.
-    'Amount' => array(
-        'value' => 9.19,                       // Amount that will be charged at the end of each cycle for this payment definition.
-        'currency' => 'USD'                    // Three Letter Currency code.
-    ),
-    'ChargeModels' => array(
-        0 => array(
-            'Type' => 'SHIPPING',              // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => 1.00,               // Amount to charge.
-                'currency' => 'USD'            // Three Letter Currency code.
-            )
-        ),
-        1 => array(
-            'Type' => 'TAX',                   // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => 2.00,               // Amount to charge.
-                'currency' => 'USD'            // Three Letter Currency code.
-            )
-        )
-    )
-);
-
-
-$baseUrl = $domain . "billing_agreements/";
-$CancelUrl = '/ExecuteAgreement.php?success=false';        // Redirect URL on cancellation of agreement request. 1000 characters max.
-$ReturnUrl = '/ExecuteAgreement.php?success=true';         // Redirect URL on creation of agreement request. 1000 characters max.
-
-// Merchant Preferences are optional for creating plan.
-$merchant_preferences = array(
-    "NotifyUrl" => '',                              // Notify URL on agreement creation. 1000 characters max.
-    "MaxFailAttempts" => '',                        // Total number of failed attempts allowed. Default is 0, representing an infinite number of failed attempts.
-    "AutoBillAmount" => 'yes',                      // Allowed values: `YES`, `NO`. Default is `NO`. Allow auto billing for the outstanding amount of the agreement in the next cycle.
-    "InitialFailAmountAction" => 'CONTINUE',        // Allowed values: `CONTINUE`, `CANCEL`. Default is continue. Action to take if a failure occurs during initial payment.
-    "AcceptedPaymentType" => '',                    // Payment types that are accepted for this plan.
-    "SetupFee" => array(
-        'value' => 1.00,                            // Setup fee amount. Default is 0.
-        'currency' => 'USD'                         // Three Letter Currency code.
-    )
-);
-
-$requestData = array(
-    "plan" => $plan,
-    "paymentDefinitions" => $paymentDefinitions,
-    "merchant_preferences" => $merchant_preferences,
-    "baseUrl" => $baseUrl,
-    "CancelUrl" => $CancelUrl,
-    "ReturnUrl" => $ReturnUrl
-);
-
-$returnArray = $PayPal->CreatePlan($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_plans/DeletePlan.php b/samples/rest/billing_plans/DeletePlan.php
deleted file mode 100644
index d1fe39dc..00000000
--- a/samples/rest/billing_plans/DeletePlan.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = 'P-5TA8920425143812EA47LOGA';                       // Required. The ID of the billing plan for delete.
-
-$returnArray = $PayPal->DeletePlan($planId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_plans/GetPlan.php b/samples/rest/billing_plans/GetPlan.php
deleted file mode 100644
index d0fbc1dc..00000000
--- a/samples/rest/billing_plans/GetPlan.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = 'P-4EM72741GL399293LUM5YCII';                       // Required. The ID of the billing plan for which to show details.
-
-$returnArray = $PayPal->GetPlan($planId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_plans/ListPlans.php b/samples/rest/billing_plans/ListPlans.php
deleted file mode 100644
index 8ee780df..00000000
--- a/samples/rest/billing_plans/ListPlans.php
+++ /dev/null
@@ -1,25 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$parameters = array(
-    'page_size'      => '10',              // The number of billing plans to list on a single page. For example, if page_size is 10, each page shows ten billing plans. A valid value is a non-negative, non-zero integer. Default is 10.
-    'page'           => '',                // The zero-indexed number of the first page to return to begin the set of pages that are returned in the response. Default is 0.
-    'status'         => 'CREATED',         // Possible values: CREATED, ACTIVE, INACTIVE, DELETED. Filters the billing plans in the response by a plan status. Value is CREATED for created plans, ACTIVE for active plans, INACTIVE for inactive plans, or DELETED for deleted plans.
-    'total_required' => ''                 // Value is yes or no. Indicates whether to return the total_items and total_pages fields in the response.  
-);
-
-$returnArray = $PayPal->ListPlans($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/billing_plans/UpdatePlan.php b/samples/rest/billing_plans/UpdatePlan.php
deleted file mode 100644
index 1a6c9330..00000000
--- a/samples/rest/billing_plans/UpdatePlan.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planid = 'P-4EM72741GL399293LUM5YCII';          // Required. The ID of the billing plan to update.
-
-$state = 'ACTIVE';                               // Allowed values: CREATED, ACTIVE, INACTIVE, and DELETED. Status of the billing plan.
-
-$items = array(
-    'op'      => 'replace',                     // Possible values: add, remove, replace, move, copy, test. The operation to perform.
-    'path'    => '/',                           // A JSON pointer. References a location in the target document where the operation is performed.
-);
-
-$returnArray = $PayPal->UpdatePlan($planid,$items,$state);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/checkout_orders/AuthorizeOrder.php b/samples/rest/checkout_orders/AuthorizeOrder.php
deleted file mode 100644
index 21ac6d32..00000000
--- a/samples/rest/checkout_orders/AuthorizeOrder.php
+++ /dev/null
@@ -1,45 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-
-/**
- * Authorizes payment for an order.
- */
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    /**
-     * You can make this call only if you specified intent=AUTHORIZE in the create order call.
-     * get order id after the payment approval from PayPal,
-     * but if you know Order id then you can directly use $order_id function to AUTHORIZE the order.
-     */
-
-    $order_id = isset($_GET['token']) ? $_GET['token'] : '';            // Required. The ID of the order for which to authorize.
-
-    $response = $PayPal->AuthorizeOrder($order_id);
-
-    echo "
";
-    print_r($response);
-    exit;
-
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
-
diff --git a/samples/rest/checkout_orders/CaptureAuthorizedPayment.php b/samples/rest/checkout_orders/CaptureAuthorizedPayment.php
deleted file mode 100644
index 787fa1f0..00000000
--- a/samples/rest/checkout_orders/CaptureAuthorizedPayment.php
+++ /dev/null
@@ -1,69 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id  = '3HT90723074597802';       // The PayPal-generated ID for the authorized payment to capture.
-
-/**
- *   To capture a portion of the full authorized amount, specify an amount.
- *   If amount is not specified, the full authorized amount is captured.
- *   The amount must be a positive number and in the same currency as the
- *   authorization against which the payment is being captured.
- */
-$amount = array(
-    'currency_code' => 'USD',
-    'value' => 17.50,              // The amount to capture.
-);
-
-$final_capture = true;            // Default : false , Indicates whether you can make additional captures against the authorized payment. Set to true if you do not intend to capture additional payments against the authorization. Set to false if you intend to capture additional payments against the authorization.
-
-$invoice_id  = 'AEINV-663';              // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
-
-/**
- * Any additional payment instructions for PayPal for Partner customers.
- * Enables features for partners and marketplaces, such as delayed disbursement and collection of a platform fee.
- * Applies during order creation for captured payments or during capture of authorized payments.
-$payment_instruction  = array(
-    'disbursement_mode' => '',
-    'platform_fees' => array(
-        'amount' => array(
-            'currency_code' => '',
-            'value' => ''
-        ),
-        'payee' => array(
-            'email_address' => '',
-            'merchant_id' => ''
-        )
-    )
-);
- */
-
-$requestArray = array(
-
-    'amount' => $amount,
-    'final_capture' => $final_capture,
-    'invoice_id' => $invoice_id,
-    //'payment_instruction' => $payment_instruction
-);
-
-
-$response = $PayPal->CaptureAuthorizedPayment($authorization_id,$requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/CaptureOrder.php b/samples/rest/checkout_orders/CaptureOrder.php
deleted file mode 100644
index 9f230294..00000000
--- a/samples/rest/checkout_orders/CaptureOrder.php
+++ /dev/null
@@ -1,43 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    /**
-     * get order id after the payment approval from PayPal,
-     * but if you know Order id then you can directly use $order_id function to capture the order.
-     */
-
-    /**
-     * Order state must be APPROVED for capturing an order.
-     */
-    $order_id = isset($_GET['token']) ? $_GET['token'] : '';            // Required
-
-    $response = $PayPal->CaptureOrder($order_id);
-
-    echo "
";
-    print_r($response);
-    exit;
-
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
-
diff --git a/samples/rest/checkout_orders/CreateAuthorizeOrder.php b/samples/rest/checkout_orders/CreateAuthorizeOrder.php
deleted file mode 100644
index c7db8ea5..00000000
--- a/samples/rest/checkout_orders/CreateAuthorizeOrder.php
+++ /dev/null
@@ -1,211 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-/**
- * The intent to either capture payment immediately or authorize a payment for an order after order creation.
- * allowed values are: CAPTURE , AUTHORIZE
- * CAPTURE. The merchant intends to capture payment immediately after the customer makes a payment.
- * AUTHORIZE. The merchant intends to authorize a payment and place funds on hold after the customer makes a payment. Authorized payments are guaranteed for up to three days but are available to capture for up to 29 days. After the three-day honor period, the original authorized payment expires and you must re-authorize the payment. You must make a separate request to capture payments on demand.
- */
-
-$intent = 'AUTHORIZE';          // Required
-
-$currency = 'USD';              // The three-character ISO-4217 currency code that identifies the currency. https://developer.paypal.com/docs/integration/direct/rest/currency-codes/
-
-$items[0] = array(
-    'sku'         => '123',                                    // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => 'Hat',                                    // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => 'Kansas City Chiefs Large Multi-Fit Hat', // The detailed item description. Maximum length: 127.
-    'quantity'    => 1,                                        // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(
-        'value' => 7.50,
-        'currency_code' => $currency
-    ),                                     // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-    'tax'         => array(
-        'value' => 0.00,
-        'currency_code' => $currency
-    ),                                     // The item tax for each unit.
-    'category'    => 'PHYSICAL_GOODS'                          // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$items[1] = array(
-    'sku'         => '678',                                 // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => 'Handbag',                             // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => 'Small, leather handbag.',             // The detailed item description. Maximum length: 127.
-    'quantity'    => 2,                                     // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(
-        'value' => 5.00,
-        'currency_code' => $currency
-    ),                                  // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-    'tax'         => array(
-        'value' => 0.00,
-        'currency_code' => $currency
-    ),                                  // The item tax for each unit.
-    'category'    => 'PHYSICAL_GOODS'                       // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$orderItems = $items;
-
-$amount = array(
-    'currency_code' => $currency,
-    'value' => 17.50,
-    'breakdown' => array(
-        'item_total' => array(          // The subtotal for all items.
-            'value' => 17.50,
-            'currency_code' => $currency
-        ),
-        'shipping' => array(            // The shipping fee for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'handling' => array(            // The handling fee for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'tax_total' => array(            // The total tax for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'insurance' => array(            // The insurance fee for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'shipping_discount' => array(    // The shipping discount for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        )
-    )
-);
-
-/**
- * For shipping_preferences
- * The possible values are:
- *   GET_FROM_FILE  -  Use the customer-provided shipping address on the PayPal site.
- *   NO_SHIPPING -  Redact the shipping address from the PayPal site. Recommended for digital goods.
- *   SET_PROVIDED_ADDRESS - Use the merchant-provided address. The customer cannot change this address on the PayPal site.
- *
- *   note : if you select SET_PROVIDED_ADDRESS then you should pass $shipping array that we have in sample as commented code
- *
- */
-
-/**
- * For landing_page , The type of landing page to show on the PayPal site for customer checkout.
- * The possible values are :
- *       LOGIN -   Default. When the customer clicks PayPal Checkout, the customer is redirected to a page to log in to PayPal and approve the payment.
- *       BILLING - When the customer clicks PayPal Checkout, the customer is redirected to a page to enter credit or debit card and other relevant billing information required to complete the purchase.
- */
-
-/**
- *  For user_action, Configures a Continue or Pay Now checkout flow.
- *  CONTINUE -  After you redirect the customer to the PayPal payment page, a Continue button appears. Use this option when the final amount is not known when the checkout flow is initiated and you want to redirect the customer to the merchant page without processing the payment.
- *  PAY_NOW - After you redirect the customer to the PayPal payment page, a Pay Now button appears. Use this option when the final amount is known when the checkout is initiated and you want to process the payment immediately when the customer clicks Pay Now.
- */
-
-$application_context = array(
-    'brand_name' => 'AngellEye INC',              // The label that overrides the business name in the PayPal account on the PayPal site.
-    'locale' => 'en-US',                          // PayPal supports a five-character code.
-    'landing_page' => 'LOGIN',                    // Allowed Values : LOGIN,BILLING
-    'shipping_preferences' => 'GET_FROM_FILE',    // Allowed Values : GET_FROM_FILE , NO_SHIPPING , SET_PROVIDED_ADDRESS
-    'user_action' => 'CONTINUE',                  // Configures a Continue or Pay Now checkout flow.
-    'payment_method' => array(
-        'payer_selected' => 'PAYPAL',                   // Values : PAYPAL,PAYPAL_CREDIT. The customer and merchant payment preferences.
-        'payee_preferred' => 'UNRESTRICTED'             // Values : UNRESTRICTED , IMMEDIATE_PAYMENT_REQUIRED
-    ),
-    'return_url' => $domain.'samples/rest/checkout_orders/AuthorizeOrder.php?success=true',  // The URL where the customer is redirected after the customer approves the payment.
-    'cancel_url' => $domain.'samples/rest/checkout_orders/AuthorizeOrder.php?success=false', // The URL where the customer is redirected after the customer cancels the payment.
-);
-
-/*
- *
- * Uncomment if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-$shipping = array(
-                'method' => 'United States Postal Service',
-                'name' => array(
-                    'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-                    'prefix' => '',              // The prefix, or title, to the party's name.
-                    'given_name' => '',          // When the party is a person, the party's given, or first, name.
-                    'surname' => '',             // When the party is a person, the party's surname or family name.
-                    'middle_name' => '',         // When the party is a person, the party's middle name.
-                    'suffix' => ''               // The suffix for the party's name.
-                ),
-                'address' => array(
-                    'address_line_1' => '123 Townsend St',
-                    'address_line_2' => 'Floor 6',
-                    'admin_area_2' => 'San Francisco',     // A city, town, or village.
-                    'admin_area_1' => 'CA',                // country
-                    'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-                    'country_code' => 'US',                // The country code.
-                ),
-            );
-*/
-
-/*
- * Payer object is optional , if you have buyer details and you want to pass it then you can uncomment the code and use $payer in request
- *
-$payer = array(             // The customer who approves and pays for the order. The customer is also known as the payer.
-    'email_address' => 'test_buyer@domain.com', // The email address of the payer.
-    'name' => array(
-        'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-        'prefix' => '',              // The prefix, or title, to the party's name.
-        'given_name' => '',          // When the party is a person, the party's given, or first, name.
-        'surname' => '',             // When the party is a person, the party's surname or family name.
-        'middle_name' => '',         // When the party is a person, the party's middle name.
-        'suffix' => ''               // The suffix for the party's name.
-    ),
-    'phone' => array(                // The phone number of the customer. Available only when you enable the Contact Telephone Number option in the Profile & Settings for the merchant's PayPal account.
-        'phone_type' => '',          // The phone type. FAX, HOME, MOBILE, OTHER, PAGER.
-        'phone_number' => array(
-            'national_number' => '', // The phone number, in its canonical international E.164 numbering plan format. Supports only the national_number property.
-        )
-    ),
-    'birth_date' => '',              // The birth date of the payer in YYYY-MM-DD format.
-    'address' => array(
-        'address_line_1' => '123 Townsend St',
-        'address_line_2' => 'Floor 6',
-        'admin_area_2' => 'San Francisco',     // A city, town, or village.
-        'admin_area_1' => 'CA',                // country
-        'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-        'country_code' => 'US',                // The country code.
-    )
-);
-*/
-
-$purchase_units  = array(
-    'reference_id' => 'default',                  // The ID for the purchase unit. Required for multiple purchase_units or if an order must be updated by using PATCH. If you omit the reference_id for an order with one purchase unit, PayPal sets the reference_id to default.
-    'description' => 'Sporting Goods',            // The purchase description. Maximum length: 127.
-    'custom_id' => 'CUST-PayPalFashions',         // The API caller-provided external ID. Used to reconcile client transactions with PayPal transactions. Appears in transaction and settlement reports but is not visible to the payer.
-    'soft_descriptor' => 'PayPalFashions',        // The payment descriptor on the payer's credit card statement. Maximum length: 22.
-    'invoice_id' => 'AEINV-'.rand(0,1000),        // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. Maximum length: 127.
-    'amount' => $amount,
-    //'shipping' => $shipping,                        // Add $shipping if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-    'items' => $orderItems
-);
-
-$requestArray = array(
-    'intent'=>$intent,
-    'application_context' => $application_context,
-    'purchase_units' => $purchase_units,
-    //'payer' => $payer
-);
-
-$response = $PayPal->CreateOrder($requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/CreateCaptureOrder.php b/samples/rest/checkout_orders/CreateCaptureOrder.php
deleted file mode 100644
index ca6b7979..00000000
--- a/samples/rest/checkout_orders/CreateCaptureOrder.php
+++ /dev/null
@@ -1,211 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-/**
- * The intent to either capture payment immediately or authorize a payment for an order after order creation.
- * allowed values are: CAPTURE , AUTHORIZE
- * CAPTURE. The merchant intends to capture payment immediately after the customer makes a payment.
- * AUTHORIZE. The merchant intends to authorize a payment and place funds on hold after the customer makes a payment. Authorized payments are guaranteed for up to three days but are available to capture for up to 29 days. After the three-day honor period, the original authorized payment expires and you must re-authorize the payment. You must make a separate request to capture payments on demand.
- */
-
-$intent = 'CAPTURE';            // Required
-
-$currency = 'USD';              // The three-character ISO-4217 currency code that identifies the currency. https://developer.paypal.com/docs/integration/direct/rest/currency-codes/
-
-$items[0] = array(
-    'sku'         => '123',                                    // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => 'Hat',                                    // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => 'Kansas City Chiefs Large Multi-Fit Hat', // The detailed item description. Maximum length: 127.
-    'quantity'    => 1,                                        // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(
-        'value' => 7.50,
-        'currency_code' => $currency
-    ),                                     // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-    'tax'         => array(
-        'value' => 0.00,
-        'currency_code' => $currency
-    ),                                     // The item tax for each unit.
-    'category'    => 'PHYSICAL_GOODS'                          // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$items[1] = array(
-    'sku'         => '678',                                 // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => 'Handbag',                             // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => 'Small, leather handbag.',             // The detailed item description. Maximum length: 127.
-    'quantity'    => 2,                                     // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(
-        'value' => 5.00,
-        'currency_code' => $currency
-    ),                                  // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-    'tax'         => array(
-        'value' => 0.00,
-        'currency_code' => $currency
-    ),                                  // The item tax for each unit.
-    'category'    => 'PHYSICAL_GOODS'                       // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$orderItems = $items;
-
-$amount = array(
-    'currency_code' => $currency,
-    'value' => 17.50,
-    'breakdown' => array(
-        'item_total' => array(          // The subtotal for all items.
-            'value' => 17.50,
-            'currency_code' => $currency
-        ),
-        'shipping' => array(            // The shipping fee for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'handling' => array(            // The handling fee for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'tax_total' => array(            // The total tax for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'insurance' => array(            // The insurance fee for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        ),
-        'shipping_discount' => array(    // The shipping discount for all items.
-            'value' => 0.00,
-            'currency_code' => $currency
-        )
-    )
-);
-
-/**
- * For shipping_preferences
- * The possible values are:
- *   GET_FROM_FILE  -  Use the customer-provided shipping address on the PayPal site.
- *   NO_SHIPPING -  Redact the shipping address from the PayPal site. Recommended for digital goods.
- *   SET_PROVIDED_ADDRESS - Use the merchant-provided address. The customer cannot change this address on the PayPal site.
- *
- *   note : if you select SET_PROVIDED_ADDRESS then you should pass $shipping array that we have in sample as commented code
- *
- */
-
-/**
- * For landing_page , The type of landing page to show on the PayPal site for customer checkout.
- * The possible values are :
- *       LOGIN -   Default. When the customer clicks PayPal Checkout, the customer is redirected to a page to log in to PayPal and approve the payment.
- *       BILLING - When the customer clicks PayPal Checkout, the customer is redirected to a page to enter credit or debit card and other relevant billing information required to complete the purchase.
- */
-
-/**
- *  For user_action, Configures a Continue or Pay Now checkout flow.
- *  CONTINUE -  After you redirect the customer to the PayPal payment page, a Continue button appears. Use this option when the final amount is not known when the checkout flow is initiated and you want to redirect the customer to the merchant page without processing the payment.
- *  PAY_NOW - After you redirect the customer to the PayPal payment page, a Pay Now button appears. Use this option when the final amount is known when the checkout is initiated and you want to process the payment immediately when the customer clicks Pay Now.
- */
-
-$application_context = array(
-    'brand_name' => 'AngellEye INC',              // The label that overrides the business name in the PayPal account on the PayPal site.
-    'locale' => 'en-US',                          // PayPal supports a five-character code.
-    'landing_page' => 'LOGIN',                    // Allowed Values : LOGIN,BILLING
-    'shipping_preferences' => 'GET_FROM_FILE',    // Allowed Values : GET_FROM_FILE , NO_SHIPPING , SET_PROVIDED_ADDRESS
-    'user_action' => 'CONTINUE',                  // Configures a Continue or Pay Now checkout flow.
-    'payment_method' => array(
-        'payer_selected' => 'PAYPAL',                   // Values : PAYPAL,PAYPAL_CREDIT. The customer and merchant payment preferences.
-        'payee_preferred' => 'UNRESTRICTED'             // Values : UNRESTRICTED , IMMEDIATE_PAYMENT_REQUIRED
-    ),
-    'return_url' => $domain.'samples/rest/checkout_orders/CaptureOrder.php?success=true',  // The URL where the customer is redirected after the customer approves the payment.
-    'cancel_url' => $domain.'samples/rest/checkout_orders/CaptureOrder.php?success=false', // The URL where the customer is redirected after the customer cancels the payment.
-);
-
-/*
- *
- * Uncomment if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-$shipping = array(
-                'method' => 'United States Postal Service',
-                'name' => array(
-                    'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-                    'prefix' => '',              // The prefix, or title, to the party's name.
-                    'given_name' => '',          // When the party is a person, the party's given, or first, name.
-                    'surname' => '',             // When the party is a person, the party's surname or family name.
-                    'middle_name' => '',         // When the party is a person, the party's middle name.
-                    'suffix' => ''               // The suffix for the party's name.
-                ),
-                'address' => array(
-                    'address_line_1' => '123 Townsend St',
-                    'address_line_2' => 'Floor 6',
-                    'admin_area_2' => 'San Francisco',     // A city, town, or village.
-                    'admin_area_1' => 'CA',                // country
-                    'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-                    'country_code' => 'US',                // The country code.
-                ),
-            );
-*/
-
-/*
- * Payer object is optional , if you have buyer details and you want to pass it then you can uncomment the code and use $payer in request
- *
-$payer = array(             // The customer who approves and pays for the order. The customer is also known as the payer.
-    'email_address' => 'test_buyer@domain.com', // The email address of the payer.
-    'name' => array(
-        'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-        'prefix' => '',              // The prefix, or title, to the party's name.
-        'given_name' => '',          // When the party is a person, the party's given, or first, name.
-        'surname' => '',             // When the party is a person, the party's surname or family name.
-        'middle_name' => '',         // When the party is a person, the party's middle name.
-        'suffix' => ''               // The suffix for the party's name.
-    ),
-    'phone' => array(                // The phone number of the customer. Available only when you enable the Contact Telephone Number option in the Profile & Settings for the merchant's PayPal account.
-        'phone_type' => '',          // The phone type. FAX, HOME, MOBILE, OTHER, PAGER.
-        'phone_number' => array(
-            'national_number' => '', // The phone number, in its canonical international E.164 numbering plan format. Supports only the national_number property.
-        )
-    ),
-    'birth_date' => '',              // The birth date of the payer in YYYY-MM-DD format.
-    'address' => array(
-        'address_line_1' => '123 Townsend St',
-        'address_line_2' => 'Floor 6',
-        'admin_area_2' => 'San Francisco',     // A city, town, or village.
-        'admin_area_1' => 'CA',                // country
-        'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-        'country_code' => 'US',                // The country code.
-    )
-);
-*/
-
-$purchase_units  = array(
-    'reference_id' => 'default',                  // The ID for the purchase unit. Required for multiple purchase_units or if an order must be updated by using PATCH. If you omit the reference_id for an order with one purchase unit, PayPal sets the reference_id to default.
-    'description' => 'Sporting Goods',            // The purchase description. Maximum length: 127.
-    'custom_id' => 'CUST-PayPalFashions',         // The API caller-provided external ID. Used to reconcile client transactions with PayPal transactions. Appears in transaction and settlement reports but is not visible to the payer.
-    'soft_descriptor' => 'PayPalFashions',        // The payment descriptor on the payer's credit card statement. Maximum length: 22.
-    'invoice_id' => 'AEINV-'.rand(0,1000),        // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. Maximum length: 127.
-    'amount' => $amount,
-    //'shipping' => $shipping,                        // Add $shipping if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-    'items' => $orderItems
-);
-
-$requestArray = array(
-    'intent'=>$intent,
-    'application_context' => $application_context,
-    'purchase_units' => $purchase_units,
-    //'payer' => $payer
-);
-
-$response = $PayPal->CreateOrder($requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/GetAuthorizePaymentDetails.php b/samples/rest/checkout_orders/GetAuthorizePaymentDetails.php
deleted file mode 100644
index bbec44a6..00000000
--- a/samples/rest/checkout_orders/GetAuthorizePaymentDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id = '3HT90723074597802';        // The ID of the authorized payment for which to show details.
-
-$response = $PayPal->GetAuthorizePaymentDetails($authorization_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/GetCapturedPaymentDetails.php b/samples/rest/checkout_orders/GetCapturedPaymentDetails.php
deleted file mode 100644
index 449079be..00000000
--- a/samples/rest/checkout_orders/GetCapturedPaymentDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$capture_id = '6X1812201H9506636';      // The PayPal-generated ID for the captured payment for which to show details.
-
-$response = $PayPal->GetCapturedPaymentDetails($capture_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/GetOrderDetails.php b/samples/rest/checkout_orders/GetOrderDetails.php
deleted file mode 100644
index 78ebd538..00000000
--- a/samples/rest/checkout_orders/GetOrderDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$order_id = '1S392574DC197382E';        // The ID of the order for which to show details.
-
-$response = $PayPal->GetOrderDetails($order_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/Reauthorize.php b/samples/rest/checkout_orders/Reauthorize.php
deleted file mode 100644
index 726b430a..00000000
--- a/samples/rest/checkout_orders/Reauthorize.php
+++ /dev/null
@@ -1,30 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id  = '3HT90723074597802';       // The PayPal-generated ID for the authorized payment to reauthorize.
-
-$amount = array(                // The amount to reauthorize for an authorized payment.
-    'currency_code' => 'USD',
-    'value' => '5.50'
-);
-$response = $PayPal->Reauthorize($authorization_id,$amount);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/RefundCapturedPayment.php b/samples/rest/checkout_orders/RefundCapturedPayment.php
deleted file mode 100644
index 7776c734..00000000
--- a/samples/rest/checkout_orders/RefundCapturedPayment.php
+++ /dev/null
@@ -1,41 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$capture_id = '0HR988556J0930621';       // The PayPal-generated ID for the captured payment to refund.
-
-$amount = array(
-    'currency_code' => 'USD',
-    'value' => 17.50,                    // The amount to refund.
-);
-
-$invoice_id = 'AEINV-323';              // Maximum length: 127. The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
-$note_to_payer = 'Defective product';   // Maximum length: 255. The reason for the refund. Appears in both the payer's transaction history and the emails that the payer receives.
-
-$requestArray = array(
-
-    'amount' => $amount,
-    'note_to_payer' => $note_to_payer,
-   
-);
-
-$response = $PayPal->RefundCapturedPayment($capture_id,$requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/ShowRefundDetails.php b/samples/rest/checkout_orders/ShowRefundDetails.php
deleted file mode 100644
index aa545a23..00000000
--- a/samples/rest/checkout_orders/ShowRefundDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$refund_id = '38729521SY562392X';       // The PayPal-generated ID for the refund for which to show details.
-
-$response = $PayPal->ShowRefundDetails($refund_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/UpdateOrder.php b/samples/rest/checkout_orders/UpdateOrder.php
deleted file mode 100644
index f6f22682..00000000
--- a/samples/rest/checkout_orders/UpdateOrder.php
+++ /dev/null
@@ -1,52 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-/**
- * Updates an order with the CREATED or APPROVED status. You cannot update an order with the COMPLETED status.
- * Read more @ https://developer.paypal.com/docs/api/orders/v2/#orders_patch
- *
- */
-$order_id = '1S392574DC197382E';    // The ID of the order to update.
-
-$patch_array = array(               // Patch Request array. Read all Patch @ https://developer.paypal.com/docs/api/orders/v2/#orders_patch
-    0 =>
-    array(
-        "op" => "replace",
-        "path" => "/purchase_units/@reference_id=='default'/amount",
-        "value" => array(
-            'currency_code' => 'USD',
-            'value' => 21.00,
-            'breakdown' => array(
-                'item_total' => array(
-                    'value' => 17.50,
-                    'currency_code' => 'USD',
-                ),
-                'shipping' => array(
-                    'value' => 3.50,
-                    'currency_code' => 'USD',
-                )
-            )
-        )
-    )
-);
-
-$returnArray = $PayPal->UpdateOrder($order_id,$patch_array);
-echo "
";
-print_r($returnArray);
-exit;
\ No newline at end of file
diff --git a/samples/rest/checkout_orders/VoidAuthorizedPayment.php b/samples/rest/checkout_orders/VoidAuthorizedPayment.php
deleted file mode 100644
index 45016437..00000000
--- a/samples/rest/checkout_orders/VoidAuthorizedPayment.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id  = '4M267563V0633653C';       // The PayPal-generated ID for the authorized payment to void.
-
-$response = $PayPal->VoidAuthorizedPayment($authorization_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/AcceptClaim.php b/samples/rest/customer-disputes/AcceptClaim.php
deleted file mode 100644
index 5dc94048..00000000
--- a/samples/rest/customer-disputes/AcceptClaim.php
+++ /dev/null
@@ -1,62 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5614';   // The ID of the dispute for which to accept a claim.
-
-
-$address_details = array(
-    'street_number' => '',     // The street number. Maximum length: 300.
-    'street_name' => '',       // The street name. Just Drury in Drury Lane. Maximum length: 300.
-    'street_type' => '',       // The street type. For example, avenue, boulevard, road, or expressway. Maximum length: 300.
-    'delivery_service' => '',  // The delivery service. Post office box, bag number, or post office name. Maximum length: 300.
-    'building_name' => '',     // A named locations that represents the premise. Usually a building name or number or collection of buildings with a common name or number. For example, Craven House.
-    'sub_building' => ''       // The first-order entity below a named building or location that represents the sub-premise. Usually a single building within a collection of buildings with a common name. Can be a flat, story, floor, room, or apartment.
-);
-
-
-$address_portable = array(
-    'address_line_1' => '',   // The first line of the address. For example, number or street. For example, 173 Drury Lane. Required for data entry and compliance and risk checks. Must contain the full address. Maximum length: 300.
-    'address_line_2' => '',   // The second line of the address. For example, suite or apartment number. Maximum length: 300.
-    'address_line_3' => '',   // The third line of the address, if needed. For example, a street complement for Brazil, direction text, such as next to Walmart, or a landmark in an Indian address. Maximum length: 300.
-    'admin_area_4'   => '',   // The neighborhood, ward, or district. Smaller than admin_area_level_3 or sub_locality. Value is: 1) The postal sorting code that is used in Guernsey and many French territories, such as French Guiana. 2) The fine-grained administrative levels in China. Maximum length: 300.
-    'admin_area_3'   => '',   // A sub-locality, suburb, neighborhood, or district. Smaller than admin_area_level_2. Value is: 1) Brazil. Suburb, bairro, or neighborhood. 2)  India. Sub-locality or district. Street name information is not always available but a sub-locality or district can be a very small area. Maximum length: 300.
-    'admin_area_2'   => '',   // A city, town, or village. Smaller than admin_area_level_1. Maximum length: 300.
-    'admin_area_1'   => '',   // The highest level sub-division in a country, which is usually a province, state, or ISO-3166-2 subdivision. Format for postal delivery. For example, CA and not California. Value, by country, is: 1) UK. A county. 2) US. A state. 3) Canada. A province. 4) Japan. A prefecture. 5) Switzerland. A kanton. Maximum length: 300.
-    'postal_code'    => '',   // The postal code, which is the zip code or equivalent. Typically required for countries with a postal code or an equivalent. Maximum length: 60.
-    'country_code'   => '',   // Minimum length: 2. Maximum length: 2. Pattern: ^([A-Z]{2}|C2)$ The two-character ISO 3166-1 code that identifies the country or region.
-    'address_details'=> array_filter($address_details)
-);
-
-$amount = array(
-    'currency_code' => '',
-    'value' => ''
-);
-        
-
-$parameters = array(
-    'note' => 'Refund to the customer.',     // The merchant's notes about the claim. PayPal can, but the customer cannot, view these notes. Minimum length: 1. Maximum length: 2000.
-    'accept_claim_reason' => '',             // DID_NOT_SHIP_ITEM | TOO_TIME_CONSUMING | LOST_IN_MAIL | NOT_ABLE_TO_WIN | COMPANY_POLICY | REASON_NOT_SET | The merchant's reason for acceptance of the customer's claim.
-    'invoice_id' => '',                      // The merchant-provided ID of the invoice for the refund. This optional value is used to map the refund to an invoice ID in the merchant's system.
-    'return_shipping_address' => array_filter($address_portable),     // Required when the customer must return an item to the merchant for the MERCHANDISE_OR_SERVICE_NOT_AS_DESCRIBED dispute reason, especially if the refund amount is less than the dispute amount.
-    'refund_amount' => array_filter($amount)               // To accept a customer's claim, the amount that the merchant agrees to refund the customer. The subsequent action depends on the amount: 1) If this amount is less than the customer-requested amount, the dispute updates to require customer acceptance. 2) If this amount is equal to or greater than the customer-requested amount, this amount is automatically refunded to the customer and the dispute closes.
-
-);
-
-$response = $PayPal->AcceptClaim($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/DisputesAppeal.php b/samples/rest/customer-disputes/DisputesAppeal.php
deleted file mode 100644
index 8aeeaa88..00000000
--- a/samples/rest/customer-disputes/DisputesAppeal.php
+++ /dev/null
@@ -1,81 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5617';   // The ID of the dispute for which to accept a claim.
-
-
-//  carrier_name enum The name of the carrier for the shipment of the transaction for this dispute. The possible values are:
-// | UPS | USPS | FEDEX | AIRBORNE_EXPRESS | DHL | AIRSURE | ROYAL_MAIL | PARCELFORCE | SWIFTAIR | OTHER | UK_PARCELFORCE 
-// | UK_ROYALMAIL_SPECIAL UK_ROYALMAIL_RECORDED | UK_ROYALMAIL_INT_SIGNED | UK_ROYALMAIL_AIRSURE | UK_UPS | UK_FEDEX 
-// | UK_AIRBORNE_EXPRESS | UK_DHL UK_OTHER | UK_CANNOT_PROV_TRACK | CA_CANADA_POST | CA_PUROLATOR | CA_CANPAR | CA_LOOMIS  
-// | CA_TNT | CA_OTHER | CA_CANNOT_PROV_TRACK DE_DP_DHL_WITHIN_EUROPE | DE_DP_DHL_T_AND_T_EXPRESS | DE_DHL_DP_INTL_SHIPMENTS | DE_GLS | DE_DPD_DELISTACK | DE_HERMES
-// | DE_UPS | DE_FEDEX | DE_TNT | DE_OTHER | FR_CHRONOPOST | FR_COLIPOSTE | FR_DHL | FR_UPS | FR_FEDEX | FR_TNT | FR_GLS | FR_OTHER
-// | IT_POSTE_ITALIA | IT_DHL | IT_UPS | IT_FEDEX | IT_TNT | IT_GLS | IT_OTHER | AU_AUSTRALIA_POST_EP_PLAT | AU_AUSTRALIA_POST_EPARCEL | | | AU_AUSTRALIA_POST_EMS AU_DHL 
-// | AU_STAR_TRACK_EXPRESS | AU_UPS | AU_FEDEX | AU_TNT | AU_TOLL_IPEC | AU_OTHER | FR_SUIVI | IT_EBOOST_SDA
-// | ES_CORREOS_DE_ESPANA | ES_DHL | ES_UPS | ES_FEDEX | ES_TNT | ES_OTHER | AT_AUSTRIAN_POST_EMS | AT_AUSTRIAN_POST_PPRIME | BE_CHRONOPOST | 
-// | BE_TAXIPOST CH_SWISS_POST_EXPRES | CH_SWISS_POST_PRIORITY | CN_CHINA_POST | HK_HONGKONG_POST | IE_AN_POST_SDS_EMS
-// | IE_AN_POST_SDS_PRIORITY | IE_AN_POST_REGISTERED | IE_AN_POST_SWIFTPOST | IN_INDIAPOST | JP_JAPANPOST | KR_KOREA_POST | NL_TPG | | SG_SINGPOST
-// | TW_CHUNGHWA_POST | CN_CHINA_POST_EMS | CN_FEDEX | CN_TNT | CN_UPS | CN_OTHER | NL_TNT | NL_DHL | NL_UPS | NL_FEDEX | NL_KIALA | BE_KIALA 
-// | PL_POCZTA_POLSKA PL_POCZTEX | PL_GLS | PL_MASTERLINK | PL_TNT | PL_DHL | PL_UPS | PL_FEDEX | JP_SAGAWA_KYUU_BIN | JP_NITTSU_PELICAN_BIN | JP_KURO_NEKO_YAMATO_UNYUU 
-// | JP_TNT | JP_DHL | JP_UPS | JP_FEDEX | NL_PICKUP | NL_INTANGIBLE | NL_ABC_MAIL | HK_FOUR_PX_EXPRESS | HK_FLYT_EXPRESS
-
-
-$tracking_info = array(
-    'carrier_name' => 'FEDEX',          // The name of the carrier for the shipment of the transaction for this dispute.
-    'carrier_name_other' => '',         // This field capture the name of carrier in free form text for unavailable carriers from existing list.
-    'tracking_url' => '',               // The URL to track the dispute-related transaction shipment.
-    'tracking_number' => '122533485'    // The number to track the dispute-related transaction shipment.
-);
-
-$refund_ids =array(
-    'refund_id' => ''                   // The ID of the refunded transaction.
-);
-
-$evidence_info = array(
-    'tracking_info' => $tracking_info,  // An array of relevant tracking information for the transaction involved in this dispute.
-    'refund_ids' => $refund_ids         // An array of refund IDs for the transaction involved in this dispute.    
-);
-
-$documents = array(
-    'name' => '',                       // The document name.
-    'size' => ''                        // The document size.
-);
-
-
-$evidences = array(
-    'evidence_type' => 'PROOF_OF_FULFILLMENT',  // PROOF_OF_FULFILLMENT | PROOF_OF_REFUND | PROOF_OF_DELIVERY_SIGNATURE | PROOF_OF_RECEIPT_COPY | RETURN_POLICY | BILLING_AGREEMENT | PROOF_OF_RESHIPMENT | ITEM_DESCRIPTION | POLICE_REPORT | AFFIDAVIT | PAID_WITH_OTHER_METHOD | COPY_OF_CONTRACT | TERMINAL_ATM_RECEIPT | PRICE_DIFFERENCE_REASON | SOURCE_CONVERSION_RATE | BANK_STATEMENT | CREDIT_DUE_REASON | REQUEST_CREDIT_RECEIPT | PROOF_OF_RETURN | CREATE | CHANGE_REASON | OTHER
-    'evidence_info' => $evidence_info,          // The evidence-related information.
-    'documents' => $documents,                  // An array of evidence documents.
-    'notes' => '',                              // Any evidence-related notes. Maximum length: 2000.
-    'item_id' => ''                             // The item ID. If the merchant provides multiple pieces of evidence and the transaction has multiple item IDs, the merchant can use this value to associate a piece of evidence with an item ID.    
-);
-
-$parameters = array(
-    'evidences' => $evidences,                  // An array of evidences for the dispute.
-);
-
-$response = $PayPal->DisputesAppeal($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/DisputesEscalate.php b/samples/rest/customer-disputes/DisputesEscalate.php
deleted file mode 100644
index fd505691..00000000
--- a/samples/rest/customer-disputes/DisputesEscalate.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5617';                                     // The ID of the dispute to escalate to a claim.
-
-$parameters = array(
-    'note' => 'Escalating to PayPal claim for resolution.',     // The merchant's notes about the claim. PayPal can, but the customer cannot, view these notes. Minimum length: 1. Maximum length: 2000.   
-);
-
-$response = $PayPal->DisputesEscalate($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/DisputesMakeOffer.php b/samples/rest/customer-disputes/DisputesMakeOffer.php
deleted file mode 100644
index 82ddbd72..00000000
--- a/samples/rest/customer-disputes/DisputesMakeOffer.php
+++ /dev/null
@@ -1,56 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5617';   // The ID of the dispute for which to make an offer.
-
-$offer_amount = array(
-    'currency_code' => 'USD',
-    'value' => '23.00'
-);
-$address_details = array(
-    'street_number' => '',     // The street number. Maximum length: 300.
-    'street_name' => '',       // The street name. Just Drury in Drury Lane. Maximum length: 300.
-    'street_type' => '',       // The street type. For example, avenue, boulevard, road, or expressway. Maximum length: 300.
-    'delivery_service' => '',  // The delivery service. Post office box, bag number, or post office name. Maximum length: 300.
-    'building_name' => '',     // A named locations that represents the premise. Usually a building name or number or collection of buildings with a common name or number. For example, Craven House.
-    'sub_building' => ''       // The first-order entity below a named building or location that represents the sub-premise. Usually a single building within a collection of buildings with a common name. Can be a flat, story, floor, room, or apartment.
-);
-$return_shipping_address = array(
-    'address_line_1' => '',   // The first line of the address. For example, number or street. For example, 173 Drury Lane. Required for data entry and compliance and risk checks. Must contain the full address. Maximum length: 300.
-    'address_line_2' => '',   // The second line of the address. For example, suite or apartment number. Maximum length: 300.
-    'address_line_3' => '',   // The third line of the address, if needed. For example, a street complement for Brazil, direction text, such as next to Walmart, or a landmark in an Indian address. Maximum length: 300.
-    'admin_area_4'   => '',   // The neighborhood, ward, or district. Smaller than admin_area_level_3 or sub_locality. Value is: 1) The postal sorting code that is used in Guernsey and many French territories, such as French Guiana. 2) The fine-grained administrative levels in China. Maximum length: 300.
-    'admin_area_3'   => '',   // A sub-locality, suburb, neighborhood, or district. Smaller than admin_area_level_2. Value is: 1) Brazil. Suburb, bairro, or neighborhood. 2)  India. Sub-locality or district. Street name information is not always available but a sub-locality or district can be a very small area. Maximum length: 300.
-    'admin_area_2'   => '',   // A city, town, or village. Smaller than admin_area_level_1. Maximum length: 300.
-    'admin_area_1'   => '',   // The highest level sub-division in a country, which is usually a province, state, or ISO-3166-2 subdivision. Format for postal delivery. For example, CA and not California. Value, by country, is: 1) UK. A county. 2) US. A state. 3) Canada. A province. 4) Japan. A prefecture. 5) Switzerland. A kanton. Maximum length: 300.
-    'postal_code'    => '',   // The postal code, which is the zip code or equivalent. Typically required for countries with a postal code or an equivalent. Maximum length: 60.
-    'country_code'   => '',   // Minimum length: 2. Maximum length: 2. Pattern: ^([A-Z]{2}|C2)$ The two-character ISO 3166-1 code that identifies the country or region.
-    'address_details'=> array_filter($address_details)
-);
-
-$parameters = array(
-    'note' => 'Offer refund with replacement item.',                    // The merchant's notes about the claim. PayPal can, but the customer cannot, view these notes. Minimum length: 1. Maximum length: 2000.   
-    'offer_amount' => array_filter($offer_amount),                      // The amount proposed to resolve the dispute.
-    'offer_type' => 'REFUND_WITH_REPLACEMENT',                          // The type of offer that the merchant proposes for the dispute. The allowed values are: REFUND | REFUND_WITH_RETURN | REFUND_WITH_REPLACEMENT
-    'invoice_id' => '',                                                 // The merchant-provided ID of the invoice for the refund. This optional value maps the refund to an invoice ID in the merchant's system.
-    'return_shipping_address' => array_filter($return_shipping_address) // The return address for the item. Required when the customer must return an item to the merchant for the MERCHANDISE_OR_SERVICE_NOT_AS_DESCRIBED dispute reason, especially if the refund amount is less than the dispute amount.
-);
-
-$response = $PayPal->DisputesMakeOffer($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/ListDisputes.php b/samples/rest/customer-disputes/ListDisputes.php
deleted file mode 100644
index 53ea636c..00000000
--- a/samples/rest/customer-disputes/ListDisputes.php
+++ /dev/null
@@ -1,34 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-/**
- *  Note for parameter : You can specify either but not both 
- *  the start_time and disputed_transaction_id query parameter. 
- *  If you omit the start time, default is the current date and time.
- */
-
-$parameters = array(
-    'disputed_transaction_id' => '2EV46355LC1739201', // Filters the disputes in the response by a transaction, by ID. You can specify either but not both the start_time and disputed_transaction_id query parameter.
-    //'start_time' => '',                             // Format yyyy-MM-ddTHH:mm:ss.SSSZ. For example 2018-10-03T09:53:06.000Z, Filters the disputes in the response by a creation date and time. The start time must be within the last 180 days. 
-    'page_size' => '1',                               // Default: 10. Minimum value: 1. Maximum value: 50. Limits the number of disputes in the response to this value.
-    'next_page_token' => '',                          // The token that describes the next page of results to fetch. The list disputes call returns this token in the HATEOAS links in the response. If you omit this parameter, the API returns the first page of data.
-    'dispute_state' => 'OPEN_INQUIRIES'               // REQUIRED_ACTION | REQUIRED_OTHER_PARTY_ACTION | UNDER_PAYPAL_REVIEW | RESOLVED | OPEN_INQUIRIES | Filters the disputes in the response by a state.   
-);
-$response = $PayPal->ListDisputes($parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/samples/rest/customer-disputes/ProvideEvidence.php b/samples/rest/customer-disputes/ProvideEvidence.php
deleted file mode 100644
index 892a8d5f..00000000
--- a/samples/rest/customer-disputes/ProvideEvidence.php
+++ /dev/null
@@ -1,85 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5617';   // The ID of the dispute for which to accept a claim.
-
-
-//  carrier_name enum The name of the carrier for the shipment of the transaction for this dispute. The possible values are:
-// | UPS | USPS | FEDEX | AIRBORNE_EXPRESS | DHL     | AIRSURE | ROYAL_MAIL | PARCELFORCE | SWIFTAIR | OTHER | UK_PARCELFORCE 
-// | UK_ROYALMAIL_SPECIAL UK_ROYALMAIL_RECORDED | UK_ROYALMAIL_INT_SIGNED | UK_ROYALMAIL_AIRSURE | UK_UPS | UK_FEDEX 
-// | UK_AIRBORNE_EXPRESS | UK_DHL UK_OTHER | UK_CANNOT_PROV_TRACK | CA_CANADA_POST | CA_PUROLATOR | CA_CANPAR | CA_LOOMIS  
-// | CA_TNT | CA_OTHER | CA_CANNOT_PROV_TRACK DE_DP_DHL_WITHIN_EUROPE | DE_DP_DHL_T_AND_T_EXPRESS | DE_DHL_DP_INTL_SHIPMENTS | DE_GLS | DE_DPD_DELISTACK | DE_HERMES
-// | DE_UPS | DE_FEDEX | DE_TNT | DE_OTHER | FR_CHRONOPOST | FR_COLIPOSTE | FR_DHL | FR_UPS | FR_FEDEX | FR_TNT | FR_GLS | FR_OTHER
-// | IT_POSTE_ITALIA | IT_DHL | IT_UPS | IT_FEDEX | IT_TNT | IT_GLS | IT_OTHER | AU_AUSTRALIA_POST_EP_PLAT | AU_AUSTRALIA_POST_EPARCEL | | | AU_AUSTRALIA_POST_EMS AU_DHL 
-// | AU_STAR_TRACK_EXPRESS | AU_UPS | AU_FEDEX | AU_TNT | AU_TOLL_IPEC | AU_OTHER | FR_SUIVI | IT_EBOOST_SDA
-// | ES_CORREOS_DE_ESPANA | ES_DHL | ES_UPS | ES_FEDEX | ES_TNT | ES_OTHER | AT_AUSTRIAN_POST_EMS | AT_AUSTRIAN_POST_PPRIME | BE_CHRONOPOST | 
-// | BE_TAXIPOST CH_SWISS_POST_EXPRES | CH_SWISS_POST_PRIORITY | CN_CHINA_POST | HK_HONGKONG_POST | IE_AN_POST_SDS_EMS
-// | IE_AN_POST_SDS_PRIORITY | IE_AN_POST_REGISTERED | IE_AN_POST_SWIFTPOST | IN_INDIAPOST | JP_JAPANPOST | KR_KOREA_POST | NL_TPG | | SG_SINGPOST
-// | TW_CHUNGHWA_POST | CN_CHINA_POST_EMS | CN_FEDEX | CN_TNT | CN_UPS | CN_OTHER | NL_TNT | NL_DHL | NL_UPS | NL_FEDEX | NL_KIALA | BE_KIALA 
-// | PL_POCZTA_POLSKA PL_POCZTEX | PL_GLS | PL_MASTERLINK | PL_TNT | PL_DHL | PL_UPS | PL_FEDEX | JP_SAGAWA_KYUU_BIN | JP_NITTSU_PELICAN_BIN | JP_KURO_NEKO_YAMATO_UNYUU 
-// | JP_TNT | JP_DHL | JP_UPS | JP_FEDEX | NL_PICKUP | NL_INTANGIBLE | NL_ABC_MAIL | HK_FOUR_PX_EXPRESS | HK_FLYT_EXPRESS
-
-
-$tracking_info = array(
-    'carrier_name' => 'FEDEX',                  // The name of the carrier for the shipment of the transaction for this dispute.
-    'carrier_name_other' => '',                 // This field capture the name of carrier in free form text for unavailable carriers from existing list.
-    'tracking_url' => '',                       // The URL to track the dispute-related transaction shipment.
-    'tracking_number' => '122533485'            // The number to track the dispute-related transaction shipment.
-);
-
-$refund_ids =array(
-    'refund_id' => ''                           // The ID of the refunded transaction.
-);
-
-$evidence_info = array(
-    'tracking_info' => $tracking_info,          // An array of relevant tracking information for the transaction involved in this dispute.
-    'refund_ids' => $refund_ids                 // An array of refund IDs for the transaction involved in this dispute.    
-);
-
-$documents = array(
-    'name' => '',                               // The document name.
-    'size' => ''                                // The document size.
-);
-
-$evidences = array(
-    'evidence_type' => 'PROOF_OF_FULFILLMENT',  // PROOF_OF_FULFILLMENT | PROOF_OF_REFUND | PROOF_OF_DELIVERY_SIGNATURE | PROOF_OF_RECEIPT_COPY | RETURN_POLICY | BILLING_AGREEMENT | PROOF_OF_RESHIPMENT | ITEM_DESCRIPTION | POLICE_REPORT | AFFIDAVIT | PAID_WITH_OTHER_METHOD | COPY_OF_CONTRACT | TERMINAL_ATM_RECEIPT | PRICE_DIFFERENCE_REASON | SOURCE_CONVERSION_RATE | BANK_STATEMENT | CREDIT_DUE_REASON | REQUEST_CREDIT_RECEIPT | PROOF_OF_RETURN | CREATE | CHANGE_REASON | OTHER
-    'evidence_info' => $evidence_info,          // The evidence-related information.
-    'documents' => $documents,                  // An array of evidence documents.
-    'notes' => '',                              // Any evidence-related notes. Maximum length: 2000.
-    'item_id' => ''                             // The item ID. If the merchant provides multiple pieces of evidence and the transaction has multiple item IDs, the merchant can use this value to associate a piece of evidence with an item ID.
-);
-
-$parameters = array(
-    'evidences' => $evidences,                  // An array of evidences for the dispute.
-);
-
-$response = $PayPal->ProvideEvidence($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/SendMessageToOtherParty.php b/samples/rest/customer-disputes/SendMessageToOtherParty.php
deleted file mode 100644
index 6ed75cfe..00000000
--- a/samples/rest/customer-disputes/SendMessageToOtherParty.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5615';   // The ID of the dispute for which to send a message.
-
-$parameters = array(
-    'message' => 'Shipment is in progress.',   // The message sent by the merchant to the other party.
-);
-
-$response = $PayPal->SendMessageToOtherParty($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/samples/rest/customer-disputes/SettleDispute.php b/samples/rest/customer-disputes/SettleDispute.php
deleted file mode 100644
index 2cada75a..00000000
--- a/samples/rest/customer-disputes/SettleDispute.php
+++ /dev/null
@@ -1,35 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5615';   // The ID of the dispute for which to accept a claim.
-
-// The outcome of the adjudication. The allowed values are:
-// SELLER_FAVOR. This will resolve the case in seller favor and outcome will be set as RESOLVED_SELLER_FAVOR
-// BUYER_FAVOR. This will resolve the case in buyer favor and outcome will be set as RESOLVED_BUYER_FAVOR
-
-$parameters = array(
-    'adjudication_outcome' => 'SELLER_FAVOR',   // The allowed values are: BUYER_FAVOR and SELLER_FAVOR The outcome of the adjudication. 
-);
-
-$response = $PayPal->SettleDispute($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/customer-disputes/ShowDisputeDetails.php b/samples/rest/customer-disputes/ShowDisputeDetails.php
deleted file mode 100644
index 40d9e230..00000000
--- a/samples/rest/customer-disputes/ShowDisputeDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5615';   // The ID of the dispute for which to show details.
-
-$response = $PayPal->ShowDisputeDetails($dispute_id);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/samples/rest/customer-disputes/UpdateDisputeStatus.php b/samples/rest/customer-disputes/UpdateDisputeStatus.php
deleted file mode 100644
index 30f47788..00000000
--- a/samples/rest/customer-disputes/UpdateDisputeStatus.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = 'PP-D-5615';   // The ID of the dispute that requires evidence.
-
-/**
- *      If action is BUYER_EVIDENCE The status updates to WAITING_FOR_BUYER_RESPONSE      
- *      If action is SELLER_EVIDENCE The status updates to WAITING_FOR_SELLER_RESPONSE 
- *  */
-
-$parameters = array(
-    'action' => 'BUYER_EVIDENCE',   // The action. Indicates whether the state change enables the customer or merchant to submit evidence:
-);
-
-$response = $PayPal->UpdateDisputeStatus($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/samples/rest/identity/GetUserConsentURL.php b/samples/rest/identity/GetUserConsentURL.php
deleted file mode 100644
index 00ac9ead..00000000
--- a/samples/rest/identity/GetUserConsentURL.php
+++ /dev/null
@@ -1,43 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\identity\IdentityAPI($configArray);
-
-$redirectUri = $domain.'samples/rest/identity/UserConsentRedirect.php?success=true';  // Uri on merchant website to where the user must be redirected to post paypal login
-
-// @param array $scope The access privileges that you are requesting for from the user. Pass empty array for all scopes.
-// If you want some basic information then you just need to include 'openid', 'profile', 'address', 'email' in the scope.
-// If you want to special permission from the user then you need to include paypalattributes and invoicing  in the scope.
-
-$Scope   = array('openid', 'profile', 'address', 'email',
-                'https://uri.paypal.com/services/paypalattributes',
-                'https://uri.paypal.com/services/invoicing'); 
-
-$requestData = array(
-    'redirectUri' => $redirectUri,
-    'scope'       => $Scope,
-);
-        
-$returnArray = $PayPal->GetUserConsentURL($requestData);
-
-echo "
";
-print_r($returnArray);
-echo "
"; - -if($sandbox){ -echo 'Click Here to Obtain User Consent'; -} -else{ - echo 'Click Here to Obtain User Consent'; -} \ No newline at end of file diff --git a/samples/rest/identity/GetUserInfo.php b/samples/rest/identity/GetUserInfo.php deleted file mode 100644 index 4ef0a339..00000000 --- a/samples/rest/identity/GetUserInfo.php +++ /dev/null @@ -1,34 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new \angelleye\PayPal\rest\identity\IdentityAPI($configArray); -// To obtain User Info, you have to follow three steps in general. -// First, you need to obtain user's consent to retrieve the information you want. -// This is explained in the example "GetUserConsentURL.php". - -// Once you get the user's consent, the end result would be long lived refresh token. -// This refresh token should be stored in a permanent storage for later use. - -// You can retrieve the refresh token by executing GetUserConsentURL.php and store the refresh token - -$refreshToken= 'R23AAGyZu3XpUNPdyUstkkEtRp6tYwz7FOvoPURXUQT-RlX28bUr2BVcTvyA5RVgTskJm68MZoC75_W5Be8DCcdLNMeL1BW5eNxxJWFk1k39yZ54giLx-xUM4TpyOH5YmaPRAIbOPDpLKHVvFzlGA'; - -$requestData = array( - 'refreshToken' => $refreshToken, -); - -$returnArray = $PayPal->GetUserInfo($requestData); -echo "
";
-print_r($returnArray);
-echo "
"; \ No newline at end of file diff --git a/samples/rest/identity/UserConsentRedirect.php b/samples/rest/identity/UserConsentRedirect.php deleted file mode 100644 index 4fd1b666..00000000 --- a/samples/rest/identity/UserConsentRedirect.php +++ /dev/null @@ -1,29 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new \angelleye\PayPal\rest\identity\IdentityAPI($configArray); - -// ### User Consent Response -// PayPal would redirect the user to the redirect_uri mentioned when creating the consent URL. -// The user would then able to retrieve the access token by getting the code, which is returned as a GET parameter. - -if (isset($_GET['success']) && $_GET['success'] == 'true') { - $code = isset($_GET['code']) ? $_GET['code'] : ''; - $returnArray = $PayPal->GetUserConsentRedirect($code); - echo "
";
-    print_r($returnArray);
-}
-else{
-    echo "Something went wrong.";
-}
\ No newline at end of file
diff --git a/samples/rest/invoice-templates/CreateInvoiceTemplate.php b/samples/rest/invoice-templates/CreateInvoiceTemplate.php
deleted file mode 100755
index ec50e1df..00000000
--- a/samples/rest/invoice-templates/CreateInvoiceTemplate.php
+++ /dev/null
@@ -1,180 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceItemArray = array();
-
-$InvoiceItem = array(
-        'Name'          => 'Nutri Bullet',                 // Name of the item. 200 characters max.
-        'Description'   => '',                             // Description of the item. 1000 characters max.
-        'Quantity'      => '1',                            // Quantity of the item. Range of -10000 to 10000.
-        'Date'          => '',                             // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6). 
-        'Discount'      => array(
-                                'Percent' => ''            // Cost in percent. Range of 0 to 100.
-                            ),
-        'UnitOfMeasure' => '',                             // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"]. The unit of measure of the item being invoiced.        
-        'UnitPrice'     => array(
-                                'Currency' => 'USD',       // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => '50.00'      // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),                             // Unit price of the item. Range of -1,000,000 to 1,000,000.
-        'Tax'           => array(
-                                'Name'    => '',
-                                'Percent' => '',    
-                            )                           
-);
-
-array_push($InvoiceItemArray, $InvoiceItem);
-
-$merchantInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',              // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => 'Test',                                      // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => 'Testerson',                                 // The merchant last name. Maximum length is 30 characters.
-    'BusinessName' => 'Testerson\'s Test Store',                // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '001',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '5032141716',                           // In-country phone number (from in E.164 format).
-    'Extension' => '',                                          // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '1234 Main St.',                                 // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                      // City name.
-    'CountryCode' => 'US',                                      // 2 letter country code.    
-    'PostalCode'  => '97217',                                   // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',              // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                          // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                          // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => 'AngellEye',                              // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                           // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => 'Business hours 10:00 AM to 7:30 PM.',  // Additional information, such as business hours. Maximum length is 40 characters.
-    'NotificationChannel' => '',                                // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '001',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '5032141717',                           // In-country phone number (from in E.164 format).
-    'Extension' => '',                                          // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                 // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                      // City name.
-    'CountryCode' => 'US',                                      // 2 letter country code.    
-    'PostalCode'  => '97217',                                   // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-
-$shippingInfo = array(
-    'FirstName' => 'Sally',                                      // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => 'Patient',                                    // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => 'Not applicable',                          // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '001',                                      // Country code (from in E.164 format).
-    'NationalNumber' => '5039871234',                            // In-country phone number (from in E.164 format).
-    'Extension' => '',                                           // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                  // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                               // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                       // City name.
-    'CountryCode' => 'US',                                       // 2 letter country code.    
-    'PostalCode'  => '97217',                                    // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                       // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$templateDataCcInfo =  '';                                       // For invoices sent by email, one or more email addresses to which to send a Cc: copy of the notification. Supports only email addresses under participant.
-
-$templateData = array(    
-    'Reference'  => '',                                          // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.    
-    'AllowPartialPayment' => '',                                 // Indicates whether the invoice allows a partial payment. If set to `false`, invoice must be paid in full. If set to `true`, the invoice allows partial payments. Default is `false`.   
-    'MinimumAmountDue' => array(
-                                'Currency' => '',                // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                 // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),    
-    'TaxCalculatedAfterDiscount'    => 'false',                  // Indicates whether tax is calculated before or after a discount. If set to `false`, the tax is calculated before a discount. If set to `true`, the tax is calculated after a discount. Default is `false`.
-    'TaxInclusive' => 'false',                                   // Default is `false`. Indicates whether the unit price includes tax. 
-    'Note'  => 'Thank you for your business.',                    // Note to the payer. 4000 characters max.
-    'MerchantMemo'  => '',                                       // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'   => 'https://www.paypalobjects.com/webstatic/i/logo/rebrand/ppcom.svg',                                  // Full URL of an external image to use as the logo. Maximum length is 4000 characters.
-    'TotalAmount' => array(
-                                'Currency' => '',                // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                 // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                     ),                                    
-);
-$templateDiscount = array(
-    'Percent' => '',                                             // The invoice level discount, as a percent or an amount value.
-);
-
-$paymentTerm = array(
-    'TermType' => '',                                            // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                             // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-$attachments = array(
-    'Name' => 'AttachmentImage',                                 // Name of the file attached. 
-    'Url'  => 'https://cdn.pixabay.com/photo/2016/09/16/19/15/gear-1674891_960_720.png' // URL of the attached file that can be downloaded.                                             // URL of the attached file that can be downloaded. 
-);
-
-
-$TemplateSettingsMetadata = array(
-    'Hidden' => 'true'                                           // Indicates whether this field should be hidden. default is false
-);
-
-$TemplateSettings = array(
-    'FieldName'         => 'items.date' ,                        // The field name (for any field in template_data) for which the corresponding display preferences will be mapped to.    
-);
-/*Required */
-$Template = array(
-    'TemplateId'    => '',                                       // Unique identifier id of the template.    
-    'Name'          => "AngellEye Template" . rand(),            // Name of the template.
-    'Default'       => 'true',                                   // Indicates that this template is merchant's default. There can be only one template which can be a default.
-    'UnitOfMeasure' => 'HOURS',                                  // Unit of measure for the template, possible values are Quantity, Hours, Amount.
-    'Custom'        => '',                                       // Indicates whether this is a custom template created by the merchant. Non custom templates are system generated    
-);
-
-$requestData = array(
-    'InvoiceItemArray' => $InvoiceItemArray,
-    'merchantInfo'     => $merchantInfo,
-    'merchantPhone'    => $merchantPhone,
-    'merchantAddress'  => $merchantAddress,
-    'billingInfo'      => $billingInfo,
-    'billingInfoPhone' => $billingInfoPhone,
-    'billingInfoAddress' => $billingInfoAddress,
-    'shippingInfo'     => $shippingInfo,
-    'shippingInfoPhone' => $shippingInfoPhone,
-    'shippingInfoAddress' => $shippingInfoAddress,
-    'templateData'      => $templateData,
-    'templateDiscount' => $templateDiscount,
-    'paymentTerm'      => $paymentTerm,
-    'attachments'      => $attachments,
-    'TemplateSettingsMetadata' => $TemplateSettingsMetadata,
-    'TemplateSettings' => $TemplateSettings,
-    'Template'         => $Template,
-    'TemplateDataCcInfo' => $templateDataCcInfo
-);
-
-$returnArray = $PayPal->CreateInvoiceTemplate($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice-templates/DeleteInvoiceTemplate.php b/samples/rest/invoice-templates/DeleteInvoiceTemplate.php
deleted file mode 100755
index cd61738c..00000000
--- a/samples/rest/invoice-templates/DeleteInvoiceTemplate.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$template_id = 'TEMP-2F480752N0057011C';    // Required. The ID of the template to delete.
-
-$returnArray = $PayPal->DeleteInvoiceTemplate($template_id);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/invoice-templates/GetAllInvoiceTemplates.php b/samples/rest/invoice-templates/GetAllInvoiceTemplates.php
deleted file mode 100755
index a8f86f17..00000000
--- a/samples/rest/invoice-templates/GetAllInvoiceTemplates.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$fields= array(
-    "fields" => "all"       // Default: all. The fields to return in the response. Value is all or none. Specify none to return only the template name, ID, and default attributes.
-    );
-
-$returnArray = $PayPal->GetAllInvoiceTemplates($fields);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice-templates/GetInvoiceTemplate.php b/samples/rest/invoice-templates/GetInvoiceTemplate.php
deleted file mode 100755
index 035f0e18..00000000
--- a/samples/rest/invoice-templates/GetInvoiceTemplate.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$templateId = 'TEMP-3GK75625L7412105X';    // Required. The ID of the invoice template for which to show details.
-
-$returnArray = $PayPal->GetInvoiceTemplate($templateId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice-templates/UpdateInvoiceTemplate.php b/samples/rest/invoice-templates/UpdateInvoiceTemplate.php
deleted file mode 100755
index 47ee4ce6..00000000
--- a/samples/rest/invoice-templates/UpdateInvoiceTemplate.php
+++ /dev/null
@@ -1,183 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$template_id = 'TEMP-831584274S0021100';                  // Required. The ID of the template to update.
-
-$InvoiceItemArray = array();
-
-$InvoiceItem = array(
-        'Name'          => '',                            // Name of the item. 200 characters max.
-        'Description'   => '',                            // Description of the item. 1000 characters max.
-        'Quantity'      => '',                            // Quantity of the item. Range of -10000 to 10000.
-        'Date'          => '',                            // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6). 
-        'Discount'      => array(
-                                'Percent' => ''           // Cost in percent. Range of 0 to 100.
-                            ),
-        'UnitOfMeasure' => '',                            // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"]. The unit of measure of the item being invoiced.        
-        'UnitPrice'     => array(
-                                'Currency' => '',         // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''          // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),                            // Unit price of the item. Range of -1,000,000 to 1,000,000.
-        'Tax'           => array(
-                                'Name'    => '',
-                                'Percent' => '',    
-                            )                           
-);
-
-array_push($InvoiceItemArray, $InvoiceItem);
-
-$merchantInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',         // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => 'Sandbox',                              // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => 'Testerson',                            // The merchant last name. Maximum length is 30 characters.
-    'BusinessName' => 'sb\'s Test Store',                  // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => 'paypal-buyer@angelleye.com',              // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                          // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                          // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => 'AE',                              // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                           // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => 'Business hours 10:00 AM to 7:30 PM.',  // Additional information, such as business hours. Maximum length is 40 characters.
-    'NotificationChannel' => '',                                // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.
-);
-
-$shippingInfo = array(
-    'FirstName' => '',                                      // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => '',                                      // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => '',                                   // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$templateDataCcInfo =  '';                                      // For invoices sent by email, one or more email addresses to which to send a Cc: copy of the notification. Supports only email addresses under participant.
-
-$templateData = array(    
-    'Reference'  => '',                                  // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.    
-    'AllowPartialPayment' => '',                         // Indicates whether the invoice allows a partial payment. If set to `false`, invoice must be paid in full. If set to `true`, the invoice allows partial payments. Default is `false`.   
-    'MinimumAmountDue' => array(
-                                'Currency' => '',                       // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),    
-    'TaxCalculatedAfterDiscount'    => '',              // Indicates whether tax is calculated before or after a discount. If set to `false`, the tax is calculated before a discount. If set to `true`, the tax is calculated after a discount. Default is `false`.
-    'TaxInclusive' => '',                               // Default is `false`. Indicates whether the unit price includes tax. 
-    'Note'  => '',                                      // Note to the payer. 4000 characters max.
-    'MerchantMemo'  => '',                              // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'   => '',                                  // Full URL of an external image to use as the logo. Maximum length is 4000 characters.
-    'TotalAmount' => array(
-                                'Currency' => '',                       // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                     ),                                    
-);
-$templateDiscount = array(
-    'Percent' => '',                                    // The invoice level discount, as a percent or an amount value.
-);
-
-
-
-$paymentTerm = array(
-    'TermType' => '',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                          // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-$attachments = array(
-    'Name' => 'AttachmentImage',                                 // Name of the file attached.
-    'Url'  => 'https://cdn.pixabay.com/photo/2016/09/16/19/15/gear-1674891_960_720.png' // URL of the attached file that can be downloaded.                                             // URL of the attached file that can be downloaded.
-);
-
-
-$TemplateSettingsMetadata = array(
-    'Hidden' => 'true'                                           // Indicates whether this field should be hidden. default is false
-);
-
-$TemplateSettings = array(
-    'FieldName'         => 'items.date' ,                        // The field name (for any field in template_data) for which the corresponding display preferences will be mapped to.
-);
-/*Required */
-$Template = array(
-    'TemplateId'    => '',                                       // Unique identifier id of the template.
-    'Name'          => "AngellEye Template" . rand(),            // Name of the template.
-    'Default'       => 'true',                                   // Indicates that this template is merchant's default. There can be only one template which can be a default.
-    'UnitOfMeasure' => 'HOURS',                                  // Unit of measure for the template, possible values are Quantity, Hours, Amount.
-    'Custom'        => '',                                       // Indicates whether this is a custom template created by the merchant. Non custom templates are system generated
-);
-
-$requestData = array(
-    'InvoiceItemArray' => $InvoiceItemArray,
-    'merchantInfo'     => $merchantInfo,
-    'merchantPhone'    => $merchantPhone,
-    'merchantAddress'  => $merchantAddress,
-    'billingInfo'      => $billingInfo,
-    'billingInfoPhone' => $billingInfoPhone,
-    'billingInfoAddress' => $billingInfoAddress,
-    'shippingInfo'     => $shippingInfo,
-    'shippingInfoPhone' => $shippingInfoPhone,
-    'shippingInfoAddress' => $shippingInfoAddress,
-    'templateData'      => $templateData,
-    'templateDiscount' => $templateDiscount,
-    'paymentTerm'      => $paymentTerm,
-    'attachments'      => $attachments,
-    'TemplateSettingsMetadata' => $TemplateSettingsMetadata,
-    'TemplateSettings' => $TemplateSettings,
-    'Template'         => $Template,
-    'TemplateDataCcInfo' => $templateDataCcInfo
-);
-
-$returnArray = $PayPal->UpdateInvoiceTemplate($template_id,$requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/CancelInvoice.php b/samples/rest/invoice/CancelInvoice.php
deleted file mode 100755
index 47ad5466..00000000
--- a/samples/rest/invoice/CancelInvoice.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$cancelNotification = array(
-    'Subject' => 'Past due',                      // Subject of the notification.
-    'Note'    => 'Canceling invoice',             // Note to the payer.
-    'SendToMerchant' => 'true',                   // Indicates whether to send a copy of the notification to the merchant.
-    'SendToPayer' => 'true',                      // Indicates whether to send a copy of the notification to the payer.
-    'CcEmails' => '',                             // Applicable for invoices created with Cc emails. If this field is not in the body, all the cc email addresses added as part of the invoice shall be notified else this field can be used to limit the list of email addresses. Note: additional email addresses are not supported.    
-);
-
-$InvoiceID = 'INV2-SFGR-48YA-YL5X-HWLZ';    // Required. Specify the ID of the invoice to cancel.
-
-$returnArray = $PayPal->CancelInvoice($cancelNotification,$InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/CreateInvoice.php b/samples/rest/invoice/CreateInvoice.php
deleted file mode 100755
index 73ae22e0..00000000
--- a/samples/rest/invoice/CreateInvoice.php
+++ /dev/null
@@ -1,207 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-// Merchant information is Required for creating new Invoice.
-$merchantInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',             // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => 'paypal',                                            // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => 'facilitator',                                         // The merchant last name. Maximum length is 30 characters.
-    'BusinessName' => 'facilitator \'s Test Store',                     // The merchant company business name. Maximum length is 100 characters.
-    'Website' => 'https://www.angelleye.com/',                      // The merchant website. Maximum length is 2048 characters.
-    'TaxId' => 'P87904347',                                         // The merchant tax ID. Maximum length is 100 characters. 
-    'AdditionalInfoLabel' => 'Business hours 10:00 AM to 7:30 PM.'  // Any additional information, such as business hours. 40 characters max. 
-);
-
-$merchantPhone = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5032141716',                               // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$merchantFax = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5032141717',                               // In-country phone number (from in E.164 format).    
-);
-
-$merchantAddress = array(
-    'Line1' => '1234 Main St.',                                     // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                          // City name.
-    'CountryCode' => 'US',                                          // 2 letter country code.    
-    'PostalCode'  => '97217',                                       // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                          // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',                  // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                              // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                              // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => 'AngellEYE',                                  // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                               // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => 'Business hours 10:00 AM to 7:30 PM.',      // Additional information, such as business hours. Maximum length is 40 characters.
-    'NotificationChannel' => '',                                    // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '001',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '5032141717',                           // In-country phone number (from in E.164 format).
-    'Extension' => '',                                          // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                 // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                      // City name.
-    'CountryCode' => 'US',                                      // 2 letter country code.    
-    'PostalCode'  => '97217',                                   // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-
-$shippingInfo = array(
-    'FirstName' => 'Sally',                                      // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => 'Patient',                                    // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => 'Not applicable',                          // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '001',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '5039871234',                           // In-country phone number (from in E.164 format).
-    'Extension' => '',                                          // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                 // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                      // City name.
-    'CountryCode' => 'US',                                      // 2 letter country code.    
-    'PostalCode'  => '97217',                                   // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$shippingCost = array(
-    'type' => 'Amount',
-    'Amount' => array (
-        'Currency' => 'USD',
-        'Value' => '20'
-    )
-);
-
-$CCDetails['Email'] = 'test.firstname@gmail.com';             // The participant email address.  
-
-$itemArray = array();
-
-$item1 = array(
-    'Name' => 'Sutures',                                         // Name of the item. 200 characters max.
-    'Description' => '',                                         // Description of the item. 1000 characters max.
-    'Quantity' => '100',                                         // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => 'USD',                     // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => '5.00'                     // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                       ),                                        // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => 'Local Tax on Sutures',     // The tax name. Maximum length is 20 characters.
-                        'Percent' => '1',                        // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                          // Tax associated with the item.
-    'Date' => '',                                                // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                           // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                       // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item1);
-
-$item2 = array(
-    'Name' => 'Injection',                                     // Name of the item. 200 characters max.
-    'Description' => '',                                       // Description of the item. 1000 characters max.
-    'Quantity' => '5',                                         // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => 'USD',                   // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => '5.00'                   // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                       ),                                      // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => 'Local Tax on Injection', // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '3',                      // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                        // Tax associated with the item.
-    'Date' => '',                                              // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '3',                        
-                    ),                                         // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                     // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item2);
-
-$paymentTerm = array(
-    'TermType' => 'NET_45',                                    // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                           // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-/**   Note : For Invoice discount 
- *   we have to add types like percent and Amount 
- *   and based on that discount will be calculated
- *   In Sample code we have added Percent type
- *   To add Amount type use this code
- *   $finalDiscountForInvoice = array(
-        'type' => 'Amount',
-        'Amount' => array (
-                    'Currency' => 'USD',
-                    'Value' => 20.00
-        ));
- * 
- */
-$finalDiscountForInvoice = array(
-        'type' => 'Percent', 
-        'Percent' => 10
-    );
-
-$today_date = date('Y-m-d T');
-$invoiceData = array(
-    'InvoiceDate' => $today_date,                             // The date when the invoice was enabled. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Note' => 'Thank you for your business',                  // Note to the payer. 4000 characters max.
-    'Number' => '',                                           // Unique number that appears on the invoice. If left blank will be auto-incremented from the last number. 25 characters max.
-    'TemplateId' => '',                                       // The template ID used for the invoice. Useful for copy functionality.   
-    'Uri' => '',                                              // URI of the invoice resource.
-    'MerchantMemo' => '',                                     // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'      => 'https://www.paypalobjects.com/webstatic/i/logo/rebrand/ppcom.svg',                                     // Full URL of an external image to use as the logo. Maximum length is 4000 characters.    
-    'Reference' => '',                                        // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.  
-    'Terms' => '',    
-    'AllowPartialPayment' => '',    
-);
-
-$requestData =array(
-    'merchantInfo'            => $merchantInfo,
-    'merchantPhone'           => $merchantPhone,
-    'merchantFax'             => $merchantFax,
-    'merchantAddress'         => $merchantAddress,
-    'billingInfo'             => $billingInfo,
-    'billingInfoPhone'        => $billingInfoPhone,
-    'billingInfoAddress'      => $billingInfoAddress,
-    'ccInfo'                  => $CCDetails,
-    'itemArray'               => $itemArray,
-    'finalDiscountForInvoice' => $finalDiscountForInvoice,
-    'shippingInfo'            => $shippingInfo,
-    'shippingInfoPhone'       => $shippingInfoPhone,
-    'shippingInfoAddress'     => $shippingInfoAddress,
-    'shippingCost'            => $shippingCost,
-    'paymentTerm'             => $paymentTerm,
-    'invoiceData'             => $invoiceData
-);
-
-$returnArray = $PayPal->CreateInvoice($requestData);
-echo "
";
-print_r($returnArray);
-
diff --git a/samples/rest/invoice/CreateThirdPartyInvoice.php b/samples/rest/invoice/CreateThirdPartyInvoice.php
deleted file mode 100644
index 1eb66072..00000000
--- a/samples/rest/invoice/CreateThirdPartyInvoice.php
+++ /dev/null
@@ -1,221 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$refreshToken = "SCNWVZfdg43XaOmoEicazpkXyda32CGnP208EkuQ_QBIrXCYMhlvORFHHyoXPT0VbEMIHYVJEm0gVf1Vf72YgJzPScBenKoVPq__y1QRT7wwJo3WYADwUW4Q5ic";
-
-$thirdPartyMerchant = "paypal-facilitator@angelleye.com";
-
-// Merchant informations is Required for creating new Invoice. 
-$merchantInfo = array(
-    'Email' => $thirdPartyMerchant,                                 // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => 'Test',                                            // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => 'Testerson',                                         // The merchant last name. Maximum length is 30 characters.
-    'BusinessName' => 'Testerson\'s Store',                     // The merchant company business name. Maximum length is 100 characters.
-    'Website' => 'https://www.angelleye.com/',                      // The merchant website. Maximum length is 2048 characters.
-    'TaxId' => 'P87904347',                                         // The merchant tax ID. Maximum length is 100 characters. 
-    'AdditionalInfoLabel' => 'Business hours 10:00 AM to 7:30 PM.'  // Any additional information, such as business hours. 40 characters max. 
-);
-
-$merchantPhone = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5032141716',                               // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$merchantFax = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5032141717',                               // In-country phone number (from in E.164 format).    
-);
-
-$merchantAddress = array(
-    'Line1' => '1234 Main St.',                                     // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                          // City name.
-    'CountryCode' => 'US',                                          // 2 letter country code.    
-    'PostalCode'  => '97217',                                       // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                          // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',                      // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                              // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                              // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => 'AngellEye',                                     // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                               // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => 'Business hours 10:00 AM to 7:30 PM.',      // Additional information, such as business hours. Maximum length is 40 characters.
-    'NotificationChannel' => '',                                    // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5032141717',                               // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                     // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                          // City name.
-    'CountryCode' => 'US',                                          // 2 letter country code.    
-    'PostalCode'  => '97217',                                       // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                          // 2 letter code for US states, and the equivalent for other countries.         
-);
-
-$shippingInfo = array(
-    'FirstName' => 'Sally',                                         // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => 'Patient',                                       // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => 'Not applicable',                             // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5039871234',                               // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                     // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                          // City name.
-    'CountryCode' => 'US',                                          // 2 letter country code.    
-    'PostalCode'  => '97217',                                       // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                          // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$shippingCost = array(
-    'type' => 'Amount',
-    'Amount' => array (
-        'Currency' => 'USD',
-        'Value' => '20'
-    )
-);
-
-$CCDetails['Email'] = 'test.firstname@gmail.com';                   // The participant email address.  
-
-$itemArray = array();
-
-$item1 = array(
-    'Name' => 'Sutures',                                            // Name of the item. 200 characters max.
-    'Description' => '',                                            // Description of the item. 1000 characters max.
-    'Quantity' => '100',                                            // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => 'USD',                        // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => '5.00'                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                       ),                                           // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => 'Local Tax on Sutures',        // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '1',                           // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                             // Tax associated with the item.
-    'Date' => '',                                                   // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                              // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                          // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item1);
-
-$item2 = array(
-    'Name' => 'Injection',                                          // Name of the item. 200 characters max.
-    'Description' => '',                                            // Description of the item. 1000 characters max.
-    'Quantity' => '5',                                              // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => 'USD',                        // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => '5.00'                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                       ),                                           // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => 'Local Tax on Injection',      // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '3',                           // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                             // Tax associated with the item.
-    'Date' => '',                                                   // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '3',                        
-                    ),                                              // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                          // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item2);
-
-$paymentTerm = array(
-    'TermType' => 'NET_45',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                                // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-/*   Note : For Invoice discount 
- *   we have to add types like percent and Amount 
- *   and based on that discount will be calculated
- *   In Sample code we have added Percent type
- *   To add Amount type use this code
- *   $finalDiscountForInvoice = array(
-        'type' => 'Amount',
-        'Amount' => array (
-                    'Currency' => 'USD',
-                    'Value' => 20.00
-        ));
- * 
- */
-$finalDiscountForInvoice = array(
-        'type' => 'Percent', 
-        'Percent' => 10
-    );
-
-$today_date = date('Y-m-d T');
-$invoiceData = array(
-    'InvoiceDate' => $today_date,                             // The date when the invoice was enabled. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Note' => 'Thank you for your business',                  // Note to the payer. 4000 characters max.
-    'Number' => '',                                           // Unique number that appears on the invoice. If left blank will be auto-incremented from the last number. 25 characters max.
-    'TemplateId' => '',                                       // The template ID used for the invoice. Useful for copy functionality.   
-    'Uri' => '',                                              // URI of the invoice resource.
-    'MerchantMemo' => '',                                     // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'      => 'https://www.paypalobjects.com/webstatic/i/logo/rebrand/ppcom.svg',                                     // Full URL of an external image to use as the logo. Maximum length is 4000 characters.    
-    'Reference' => '',                                        // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.  
-    'Terms' => '',    
-    'AllowPartialPayment' => '',    
-);
-
-
-$requestData =array(
-    'merchantInfo'            => $merchantInfo,
-    'merchantPhone'           => $merchantPhone,
-    'merchantFax'             => $merchantFax,
-    'merchantAddress'         => $merchantAddress,
-    'billingInfo'             => $billingInfo,
-    'billingInfoPhone'        => $billingInfoPhone,
-    'billingInfoAddress'      => $billingInfoAddress,
-    'ccInfo'                  => $CCDetails,
-    'itemArray'               => $itemArray,
-    'finalDiscountForInvoice' => $finalDiscountForInvoice,
-    'shippingInfo'            => $shippingInfo,
-    'shippingInfoPhone'       => $shippingInfoPhone,
-    'shippingInfoAddress'     => $shippingInfoAddress,
-    'shippingCost'            => $shippingCost,
-    'paymentTerm'             => $paymentTerm,
-    'invoiceData'             => $invoiceData
-);
-
-$returnArray = $PayPal->CreateInvoice($requestData,true,$refreshToken);
-echo "
";
-print_r($returnArray);
-
-
diff --git a/samples/rest/invoice/DeleteInvoice.php b/samples/rest/invoice/DeleteInvoice.php
deleted file mode 100755
index f0f3b1dc..00000000
--- a/samples/rest/invoice/DeleteInvoice.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = 'INV2-G69Z-7NQ7-QRLN-EWP2';    // Required.  The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->DeleteInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/invoice/GetInvoice.php b/samples/rest/invoice/GetInvoice.php
deleted file mode 100755
index d13f72e7..00000000
--- a/samples/rest/invoice/GetInvoice.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = 'INV2-BDWB-GSEF-KKVN-UNHF';    //Required. The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->GetInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/GetNextInvoiceNumber.php b/samples/rest/invoice/GetNextInvoiceNumber.php
deleted file mode 100755
index cd4007ef..00000000
--- a/samples/rest/invoice/GetNextInvoiceNumber.php
+++ /dev/null
@@ -1,18 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$returnArray = $PayPal->GetNextInvoiceNumber();
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/GetThirdPartyInvoice.php b/samples/rest/invoice/GetThirdPartyInvoice.php
deleted file mode 100644
index c0c65256..00000000
--- a/samples/rest/invoice/GetThirdPartyInvoice.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$refreshToken = "SCNWVZfdg43XaOmoEicazpkXyda32CGnP208EkuQ_QBIrXCYMhlvORFHHyoXPT0VbEMIHYVJEm0gVf1Vf72YgJzPScBenKoVPq__y1QRT7wwJo3WYADwUW4Q5ic";
-
-$invoiceId = 'INV2-GALN-A78F-EFUB-YT74';    //Required. The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->GetThirdPartyInvoice($invoiceId,$refreshToken);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/ListInvoice.php b/samples/rest/invoice/ListInvoice.php
deleted file mode 100755
index 8627dab6..00000000
--- a/samples/rest/invoice/ListInvoice.php
+++ /dev/null
@@ -1,24 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$parameters = array(
-    'page'                  => '0',                // A zero-relative index of the list of merchant invoices.
-    'page_size'             => '4',                // The number of invoices to list beginning with the specified page.
-    'total_count_required' => 'true'             // Indicates whether the total count appears in the response. Default is false.
-);
-
-$returnArray = $PayPal->ListInvoice($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/RecordPayment.php b/samples/rest/invoice/RecordPayment.php
deleted file mode 100755
index 23312643..00000000
--- a/samples/rest/invoice/RecordPayment.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$record = array(
-    'Method' => 'CASH',                                    // Valid Values: ["BANK_TRANSFER", "CASH", "CHECK", "CREDIT_CARD", "DEBIT_CARD", "PAYPAL", "WIRE_TRANSFER", "OTHER"].  The payment mode or method. Required with the `EXTERNAL` payment type.
-    'Note'   => 'Cash received.',                          // Optional. A note associated with the payment.
-    'Date'   => '2019-01-06 03:30:00 PST',                 // The date when the invoice was paid. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-
-$amount = array(
-    'currency' => 'USD',                                   // The three-letter ISO 4217 alphabetic currency code. 
-    'value'    => '19.51'                                  // The amount up to N digits after the decimal separator, as defined in ISO 4217 for the appropriate currency code. 
-);
-
-$invoiceId = 'INV2-BDWB-GSEF-KKVN-UNHF';                   // Required. The ID of the invoice to mark as paid.
-
-$returnArray = $PayPal->RecordPayment($invoiceId,$record,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/RecordRefund.php b/samples/rest/invoice/RecordRefund.php
deleted file mode 100755
index e41d4410..00000000
--- a/samples/rest/invoice/RecordRefund.php
+++ /dev/null
@@ -1,39 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$invoiceId = 'INV2-BDWB-GSEF-KKVN-UNHF';                        // Required. Inovoice id for which to record refunds.
-
-$refundDetail = array(
-    'Type' => '',                                                // Valid Values: ["PAYPAL", "EXTERNAL"] The PayPal refund type. Indicates whether refund was paid in invoicing flow through PayPal or externally. In the case of mark-as-refunded API, the supported refund type is `EXTERNAL`. For backward compatability, the `PAYPAL` refund type is still supported.
-    'TransactionId' => '',                                       // The PayPal refund transaction ID. Required with the `PAYPAL` refund type.
-    'Date'   => '2019-01-06 03:36:00 PST',                       // Date on which the invoice was refunded. Date format: yyyy-MM-dd z. For example, 2014-02-27 PST.
-    'Note'   => 'Refund provided by cash.',                      // Optional note associated with the refund.    
-);
-
-//Amount to be recorded as refund against invoice. If this field is not passed, the total invoice paid amount is recorded as refund.
-$amount = array(
-    'currency' => 'USD',                                        // The three-letter ISO 4217 alphabetic currency code. 
-    'value'    => '19.51'                                       // The amount up to N digits after the decimal separator, as defined in ISO 4217 for the appropriate currency code. 
-);
-
-$requestData = array(
-    'invoiceId' => $invoiceId,
-    'refundDetail' => $refundDetail,
-    'amount' => $amount
-);
-
-$returnArray = $PayPal->RecordRefund($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/RemindInvoice.php b/samples/rest/invoice/RemindInvoice.php
deleted file mode 100755
index 15bcc85a..00000000
--- a/samples/rest/invoice/RemindInvoice.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$remindNotification = array(
-    'Subject' => 'Past due',                        // Subject of the notification.
-    'Note'    => 'Please pay soon',                 // Note to the payer.
-    'SendToMerchant' => 'true',                     // Indicates whether to send a copy of the notification to the merchant.
-    'SendToPayer' => '',                            // Indicates whether to send a copy of the notification to the payer.
-    'CcEmails' => '',                               // Applicable for invoices created with Cc emails. If this field is not in the body, all the cc email addresses added as part of the invoice shall be notified else this field can be used to limit the list of email addresses. Note: additional email addresses are not supported.    
-);
-
-$InvoiceID = 'INV2-JZ52-L8SK-U4L2-RF8M';            // Required. Specify the ID of the invoice to remind.
-
-$returnArray = $PayPal->RemindInvoice($remindNotification,$InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/RetrieveQRCode.php b/samples/rest/invoice/RetrieveQRCode.php
deleted file mode 100755
index 7cb7760f..00000000
--- a/samples/rest/invoice/RetrieveQRCode.php
+++ /dev/null
@@ -1,29 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$parameters = array(
-    'width'  => '300',                              // The width, in pixels, of the QR code image. Valid value is from 150 to 500. Default is 500.Default: 500.
-    'height' => '300',                              // The height, in pixels, of the QR code image. Valid value is from 150 to 500. Default is 500.Default: 500.
-    'action' => '',                                 // Default: pay. The type of URL for which to generate a QR code. Default is pay and is the only supported value.
-);
-
-$InvoiceID = 'INV2-JZ52-L8SK-U4L2-RF8M';            // Required. Specify the ID of the invoice to remind.
-
-$path = 'images/sample.png';                        // Path to save Image.
-
-$returnArray = $PayPal->RetrieveQRCode($parameters,$InvoiceID,$path);
-echo "
";
-print_r($returnArray);
-echo 'Invoice QR Code';
diff --git a/samples/rest/invoice/SearchInvoices.php b/samples/rest/invoice/SearchInvoices.php
deleted file mode 100755
index db087ec3..00000000
--- a/samples/rest/invoice/SearchInvoices.php
+++ /dev/null
@@ -1,38 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$parameters = array(
-    'email'                   => '',             // The initial letters of the email address.
-    'recipient_first_name'    => '' ,            // The initial letters of the recipient's first name.
-    'recipient_last_name'     => '',             // The initial letters of the recipient last name.
-    'recipient_business_name' => '',             // The initial letters of the recipient business name.
-    'number'                  => '',               // The invoice number.    
-    'start_invoice_date'      => '2010-05-10 PST',             // The start date for the invoice. Date format is yyyy-MM-dd z, as defined in Internet Date/Time Format.
-    'end_invoice_date'        => '2019-12-25 PST',             // The end date for the invoice. Date format is yyyy-MM-dd z, as defined in Internet Date/Time Format.
-    'start_due_date'          => '',             // The start due date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'end_due_date'            => '',             // The end due date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).  
-    'start_payment_date'      => '',             // The start payment date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6). 
-    'end_payment_date'        => '',             // The end payment date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'start_creation_date'     => '',             // The start creation date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'end_creation_date'       => '',             // The end creation date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).    
-    'page'                    => '1',            // The offset for the search results.
-    'page_size'               => '20',           // The page size for the search results.  
-    'total_count_required'    => 'true',         // Indicates whether the total count appears in the response. Default is `false`.    
-    'archived'                => '',             // A flag indicating whether search is on invoices archived by merchant. true - returns archived / false returns unarchived / null returns all.    
-);
-
-$returnArray = $PayPal->SearchInvoices($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/SendInvoice.php b/samples/rest/invoice/SendInvoice.php
deleted file mode 100755
index 615692a3..00000000
--- a/samples/rest/invoice/SendInvoice.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = 'INV2-JZ52-L8SK-U4L2-RF8M';    // Required. The ID of the invoice to send.
-
-$returnArray = $PayPal->SendInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice/UpdateInvoice.php b/samples/rest/invoice/UpdateInvoice.php
deleted file mode 100755
index a882dcb7..00000000
--- a/samples/rest/invoice/UpdateInvoice.php
+++ /dev/null
@@ -1,179 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = 'INV2-JZ52-L8SK-U4L2-RF8M';                       // Required. The ID of the invoice to update.
-
-$merchantInfo = array(
-    'Email' => 'sandbox@givewhen.com',              // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => 'Test',                                      // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => 'Testerson',                                 // The merchant last name. Maximum length is 30 characters.
-    'BusinessName' => 'Testerson\'s store',                     // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '001',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '5032141716',                           // In-country phone number (from in E.164 format).
-    'Extension' => '',                                          // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '1234 Main St.',                                 // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                      // City name.
-    'CountryCode' => 'US',                                      // 2 letter country code.    
-    'PostalCode'  => '97217',                                   // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => 'paypal-facilitator@angelleye.com',              // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                          // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                          // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => 'AngellEye',                              // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                           // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => 'Business hours 10:00 AM to 7:30 PM.',  // Additional information, such as business hours. Maximum length is 40 characters.
-    'NotificationChannel' => '',                                // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '001',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '5032141717',                           // In-country phone number (from in E.164 format).
-    'Extension' => '',                                          // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                 // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                      // City name.
-    'CountryCode' => 'US',                                      // 2 letter country code.    
-    'PostalCode'  => '97217',                                   // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-  
-$itemArray = array();
-
-$item1 = array(
-    'Name' => 'Sutures',                                        // Name of the item. 200 characters max.
-    'Description' => '',                                        // Description of the item. 1000 characters max.
-    'Quantity' => '100',                                        // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => 'USD',                    // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => '5.00'                    // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                       ),                                       // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => 'Local Tax on Sutures',    // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '1',                       // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                         // Tax associated with the item.
-    'Date' => '',                                               // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                          // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                      // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item1);
-
-$item2 = array(
-    'Name' => 'Injection',                                          // Name of the item. 200 characters max.
-    'Description' => '',                                            // Description of the item. 1000 characters max.
-    'Quantity' => '5',                                              // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => 'USD',                        // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => '5.00'                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                       ),                                           // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => 'Local Tax on Injection',      // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '3',                           // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                             // Tax associated with the item.
-    'Date' => '',                                                   // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => null,                        
-                    ),                                              // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                          // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item2);
-
-$finalDiscountForInvoice = array(
-    'type' => 'Percent',
-    'Percent' => '2'                                                // The rate of the specified Discount. Valid range is from 0.001 to 99.999.                         
-);
-
-$shippingInfo = array(
-    'FirstName' => 'Sally',                                         // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => 'Patient',                                       // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => 'Not applicable',                             // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '001',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '5039871234',                               // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '1234 Main St.',                                     // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => 'Portland',                                          // City name.
-    'CountryCode' => 'US',                                          // 2 letter country code.    
-    'PostalCode'  => '97217',                                       // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => 'OR',                                          // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$paymentTerm = array(
-    'TermType' => 'NET_45',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                                // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-$invoiceData = array(
-    'Note' => 'Thank you for your Payment',                         // Note to the payer. 4000 characters max.
-    'Number' => '',                                                 // Unique number that appears on the invoice. If left blank will be auto-incremented from the last number. 25 characters max.
-    'TemplateId' => '',                                             // The template ID used for the invoice. Useful for copy functionality.   
-    'Uri' => '',                                                    // URI of the invoice resource.
-    'MerchantMemo' => '',                                           // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'      => 'https://www.paypalobjects.com/webstatic/i/logo/rebrand/ppcom.svg',                                     // Full URL of an external image to use as the logo. Maximum length is 4000 characters.    
-);
-
-$attachments = array(
-    0 => array(
-        'Name' => 'AttachmentImage',                                    // Name of the file attached.
-        'Url'  => 'https://cdn.pixabay.com/photo/2016/09/16/19/15/gear-1674891_960_720.png' // URL of the attached file that can be downloaded.                                             // URL of the attached file that can be downloaded.
-    )
-);
-
-$requestData =array(
-    'merchantInfo'            => $merchantInfo,
-    'merchantPhone'           => $merchantPhone,
-    'merchantAddress'         => $merchantAddress,
-    'billingInfo'             => $billingInfo,
-    'billingInfoPhone'        => $billingInfoPhone,
-    'billingInfoAddress'      => $billingInfoAddress,
-    'itemArray'               => $itemArray,
-    'finalDiscountForInvoice' => $finalDiscountForInvoice,
-    'shippingInfo'            => $shippingInfo,
-    'shippingInfoPhone'       => $shippingInfoPhone,
-    'shippingInfoAddress'     => $shippingInfoAddress,
-    'paymentTerm'             => $paymentTerm,
-    'invoiceData'             => $invoiceData,
-    'InvoiceID'               => $InvoiceID,
-    'attachments'             => $attachments
-);
-
-$returnArray = $PayPal->UpdateInvoice($requestData);
-echo "
";
-print_r($returnArray);
-
diff --git a/samples/rest/invoice/images/sample.png b/samples/rest/invoice/images/sample.png
deleted file mode 100755
index 18e143471a29342a9f96b03e9198032950898f10..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 625
zcmV-%0*?KOP)@nH}w%VbYwlLTTqL4rs}0unIf2hk6_xO_2WtMKgUm6*uoaJu!Tjy
zda~oNGxuFCsawlsuXc5hh1ut-*eO-7cidI@^jncIy<3mHZVD^V(%DoQd+-Q}rF@B$
zWK4k|Q88U;Y58(Zz6vrqh9KWf4ZXGL(#!XEVQP%Vg*g9xe)hMSF+Xg%O&JwL1O98y
zni=bwgA$gzCE6DkUBA9{n;+YG+Hz|?G7LaTxd+4iEzSk+GV{@aXDucn0Rap#}OPlSu%p5MZ!7~ZZc;!O<>Mwf5skgehit2$;bn{S%HxTC!Zg4m%gVi
zPpe*b35QucQ{C&#>#MKXd2mHRmTJ%kB>@wYP>
zakh3?8lq9h!tMdMwE!GbAmL&QAQ;B&8=o(g#DIrN5)eCYO&H|GTfB%^JuC~t7)d;7-cilH#ysCr!5Cr;(_e%8d;`islL7Phd3#mD{uEyC=e{hST!00000
LNkvXXu0mjfHgOz5

diff --git a/samples/rest/invoice_v2/CancelInvoice.php b/samples/rest/invoice_v2/CancelInvoice.php
deleted file mode 100644
index 92e7cb61..00000000
--- a/samples/rest/invoice_v2/CancelInvoice.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new InvoiceAPIv2($configArray);
-
-$cancelNotification = array(
-    'subject' => 'Past due',                      // Subject of the notification.
-    'note'    => 'Canceling invoice',             // Note to the payer.
-    'send_to_invoicer' => true,                   // Indicates whether to send a copy of the notification to the merchant.
-    'send_to_recipient' => true,                  // Indicates whether to send a copy of the notification to the payer.
-    'additional_recipients' => array(),             // Applicable for invoices created with Cc emails. If this field is not in the body, all the cc email addresses added as part of the invoice shall be notified else this field can be used to limit the list of email addresses. Note: additional email addresses are not supported.    
-);
-
-$InvoiceID = 'INV2-YZZF-D7VN-P2YM-9ZH2';          // Required. Specify the ID of the invoice to cancel.
-
-$returnArray = $PayPal->CancelInvoice($cancelNotification,$InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice_v2/DeleteInvoice.php b/samples/rest/invoice_v2/DeleteInvoice.php
deleted file mode 100644
index 00f2c07f..00000000
--- a/samples/rest/invoice_v2/DeleteInvoice.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new InvoiceAPIv2($configArray);
-
-$InvoiceID = 'INV2-YZZF-D7VN-P2YM-9ZH2';    // Required.  The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->DeleteInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/invoice_v2/GetInvoice.php b/samples/rest/invoice_v2/GetInvoice.php
deleted file mode 100644
index b5571842..00000000
--- a/samples/rest/invoice_v2/GetInvoice.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new InvoiceAPIv2($configArray);;
-$InvoiceID = 'INV2-9LG8-P8ZN-4MPN-F5PA';    //Required. The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->GetInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
-
diff --git a/samples/rest/invoice_v2/GetNextInvoiceNumber.php b/samples/rest/invoice_v2/GetNextInvoiceNumber.php
deleted file mode 100644
index 2741ff71..00000000
--- a/samples/rest/invoice_v2/GetNextInvoiceNumber.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new InvoiceAPIv2($configArray);
-
-$returnArray = $PayPal->GetNextInvoiceNumber();
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice_v2/ListInvoice.php b/samples/rest/invoice_v2/ListInvoice.php
deleted file mode 100644
index bae484a2..00000000
--- a/samples/rest/invoice_v2/ListInvoice.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-$PayPal = new InvoiceAPIv2($configArray);
-
-$parameters = array(
-    'page'                  => '0',                // A zero-relative index of the list of merchant invoices.
-    'page_size'             => '4',                // The number of invoices to list beginning with the specified page.
-    'total_count_required ' => 'true',             // Indicates whether the total count appears in the response. Default is false.
-);
-
-$returnArray = $PayPal->ListInvoice($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/invoice_v2/SendInvoice.php b/samples/rest/invoice_v2/SendInvoice.php
deleted file mode 100644
index 339cde4d..00000000
--- a/samples/rest/invoice_v2/SendInvoice.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new InvoiceAPIv2($configArray);
-
-$InvoiceID = 'INV2-YZZF-D7VN-P2YM-9ZH2';    // Required. The ID of the invoice to send.
-
-$returnArray = $PayPal->SendInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/notifications/CreateWebhook.php b/samples/rest/notifications/CreateWebhook.php
deleted file mode 100644
index d71de831..00000000
--- a/samples/rest/notifications/CreateWebhook.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$event_types = array(
-    'VAULT.CREDIT-CARD.CREATED', // The unique event name. You can fine list of webhooks name in PayPal_Webhooks.txt
-    'VAULT.CREDIT-CARD.DELETED'  // The unique event name. You can fine list of webhooks name in PayPal_Webhooks.txt
-);
-
-$url = "https://dev.aetesting.xyz/?angelleye_paypal_webhooks&action=webhook_handler";          // The URL that is configured to listen on localhost for incoming POST notification messages that contain event information.
-
-$requestData = array(
-    'Url' => $url,
-    'EventTypes' => $event_types
-);
-
-$returnArray = $PayPal->CreateWebhook($requestData);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/DeleteWebhook.php b/samples/rest/notifications/DeleteWebhook.php
deleted file mode 100644
index 22d3cfb6..00000000
--- a/samples/rest/notifications/DeleteWebhook.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '6PN687461P1543922';  // The ID of the webhook to delete.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-
-$PayPalResult = $PayPal->DeleteWebhook($webhook_id);
-
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/notifications/EventNotificationDetails.php b/samples/rest/notifications/EventNotificationDetails.php
deleted file mode 100644
index 26eb7d29..00000000
--- a/samples/rest/notifications/EventNotificationDetails.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$event_id  = 'WH-5SS08699HS6050426-3BR83168DE826290U';     // The ID of the webhook event notification for which to show details.
-
-$returnArray = $PayPal->EventNotificationDetails($event_id);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/GetWebhook.php b/samples/rest/notifications/GetWebhook.php
deleted file mode 100644
index 9a70166d..00000000
--- a/samples/rest/notifications/GetWebhook.php
+++ /dev/null
@@ -1,24 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '8EL46366UX208650W';  // The ID of the webhook for which to show details.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->GetWebhook($webhook_id);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/notifications/ListEventSubscriptionsForWebhook.php b/samples/rest/notifications/ListEventSubscriptionsForWebhook.php
deleted file mode 100644
index 1efd9751..00000000
--- a/samples/rest/notifications/ListEventSubscriptionsForWebhook.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '8EL46366UX208650W'; //  The ID of the webhook for which to list subscriptions.
-
-$returnArray = $PayPal->WebhooksEventTypesById($webhook_id);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/ListWebhooks.php b/samples/rest/notifications/ListWebhooks.php
deleted file mode 100644
index da169a9c..00000000
--- a/samples/rest/notifications/ListWebhooks.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$anchor_type = 'APPLICATION'; // Allowed values: APPLICATION, ACCOUNT. Default: APPLICATION. Filters the webhooks in the response by the anchor_id entity type.
-$requestData['anchor_type'] = $anchor_type;
-
-$returnArray = $PayPal->ListWebhooks($requestData);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/PayPal_Webhooks.txt b/samples/rest/notifications/PayPal_Webhooks.txt
deleted file mode 100644
index e532dda2..00000000
--- a/samples/rest/notifications/PayPal_Webhooks.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-BILLING.PLAN.CREATED
-BILLING.PLAN.UPDATED
-BILLING.SUBSCRIPTION.CANCELLED
-BILLING.SUBSCRIPTION.CREATED
-BILLING.SUBSCRIPTION.RE-ACTIVATED
-BILLING.SUBSCRIPTION.SUSPENDED
-BILLING.SUBSCRIPTION.UPDATED
-CHECKOUT.ORDER.COMPLETED
-CUSTOMER.DISPUTE.CREATED
-CUSTOMER.DISPUTE.RESOLVED
-CUSTOMER.DISPUTE.UPDATED
-CUSTOMER.MANAGED-ACCOUNT.CREATED
-CUSTOMER.MANAGED-ACCOUNT.RISK-ASSESSED
-CUSTOMER.MANAGED-ACCOUNT.UPDATED
-CUSTOMER.PAYOUT.FAILED
-IDENTITY.AUTHORIZATION-CONSENT.REVOKED
-INVOICING.INVOICE.CANCELLED
-INVOICING.INVOICE.CREATED
-INVOICING.INVOICE.PAID
-INVOICING.INVOICE.REFUNDED
-INVOICING.INVOICE.SCHEDULED
-INVOICING.INVOICE.UPDATED
-MERCHANT.ONBOARDING.COMPLETED
-MERCHANT.PARTNER-CONSENT.REVOKED
-PAYMENT-NETWORKS.ALTERNATIVE-PAYMENT.COMPLETED
-PAYMENT.AUTHORIZATION.CREATED
-PAYMENT.AUTHORIZATION.VOIDED
-PAYMENT.CAPTURE.COMPLETED
-PAYMENT.CAPTURE.DENIED
-PAYMENT.CAPTURE.PENDING
-PAYMENT.CAPTURE.REFUNDED
-PAYMENT.CAPTURE.REVERSED
-PAYMENT.ORDER.CANCELLED
-PAYMENT.ORDER.CREATED
-PAYMENT.PAYOUTS-ITEM.BLOCKED
-PAYMENT.PAYOUTS-ITEM.CANCELED
-PAYMENT.PAYOUTS-ITEM.DENIED
-PAYMENT.PAYOUTS-ITEM.FAILED
-PAYMENT.PAYOUTS-ITEM.HELD
-PAYMENT.PAYOUTS-ITEM.REFUNDED
-PAYMENT.PAYOUTS-ITEM.RETURNED
-PAYMENT.PAYOUTS-ITEM.SUCCEEDED
-PAYMENT.PAYOUTS-ITEM.UNCLAIMED
-PAYMENT.PAYOUTSBATCH.DENIED
-PAYMENT.PAYOUTSBATCH.PROCESSING
-PAYMENT.PAYOUTSBATCH.SUCCESS
-PAYMENT.SALE.COMPLETED
-PAYMENT.SALE.DENIED
-PAYMENT.SALE.PENDING
-PAYMENT.SALE.REFUNDED
-PAYMENT.SALE.REVERSED
-RISK.DISPUTE.CREATED
-VAULT.CREDIT-CARD.CREATED
-VAULT.CREDIT-CARD.DELETED
-VAULT.CREDIT-CARD.UPDATED
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/samples/rest/notifications/ResendEventNotification.php b/samples/rest/notifications/ResendEventNotification.php
deleted file mode 100644
index 9a5ac544..00000000
--- a/samples/rest/notifications/ResendEventNotification.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$event_id  = 'WH-5SS08699HS6050426-3BR83168DE826290U';     // The ID of the webhook event notification for which to show details.
-
-$returnArray = $PayPal->ResendEventNotification($event_id);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/SearchWebhookEvents.php b/samples/rest/notifications/SearchWebhookEvents.php
deleted file mode 100644
index f7bb2afc..00000000
--- a/samples/rest/notifications/SearchWebhookEvents.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$params = array(
-    'start_time'=>'2018-10-01T11:00:00Z',           // Filters the webhook event notifications in the response to those created on or after this date and time and on or before the end_time value.
-    'end_time'=>'2018-10-30T11:00:00Z',             // Filters the webhook event notifications in the response to those created on or after the start_time and on or before this date and time.
-    'page_size' => '10',                            // Default: 10. The number of webhook event notifications to return in the response.
-    'transaction_id' => '',                         // Filters the response to a single transaction, by ID.
-    'event_type' =>'VAULT.CREDIT-CARD.CREATED'      // Filters the response to a single event.
-);
-
-$returnArray = $PayPal->SearchWebhookEvents($params);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/SimulateEvent.php b/samples/rest/notifications/SimulateEvent.php
deleted file mode 100644
index 90ad6b77..00000000
--- a/samples/rest/notifications/SimulateEvent.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$params = array(
-    'webhook_id'=>'',                                 // The ID of the webhook. If omitted, the URL is required.
-    'url'=>'https://example.com/example_webhook',     // The URL for the webhook endpoint. If omitted, the webhook ID is required.
-    'event_type' => 'PAYMENT.AUTHORIZATION.CREATED',  // The event name. Specify one of the subscribed events. For each request, provide only one event.
-    'resource_version' => '1.0',                      // The identifier for event type ex: 1.0/2.0 etc.
-);
-
-$returnArray = $PayPal->SimulateEvent($params);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/UpdateWebhook.php b/samples/rest/notifications/UpdateWebhook.php
deleted file mode 100644
index 619cd6c2..00000000
--- a/samples/rest/notifications/UpdateWebhook.php
+++ /dev/null
@@ -1,38 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '9F037003R3934961K';                           // The ID of the webhook to update.
-
-$requestData = array(
-    array(
-        'Op' => 'replace',                                   // The operation to complete. Valid Values: ["add", "remove", "replace", test"]
-        'Path'      => '/url',                               // The JSON pointer to the target document location at which to complete the operation.
-        'Value'     => "https://requestb.in/10ujt3c1?uniqid=". uniqid()  // The value to apply. The remove operation does not require a value.
-    ),
-    array(
-        'Op' => 'replace',                                   // The operation to complete. Valid Values: ["add", "remove", "replace", test"]
-        'Path'      => '/event_types',                       // The JSON pointer to the target document location at which to complete the operation.
-        'Value'     => array(
-            'PAYMENT.SALE.REFUNDED',
-            'PAYMENT.SALE.REVERSED',
-            'RISK.DISPUTE.CREATED'
-        )               // The value to apply. The remove operation does not require a value.
-    )
-);
-
-$returnArray = $PayPal->UpdateWebhook($webhook_id,$requestData);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/VerifyWebhookSignature.php b/samples/rest/notifications/VerifyWebhookSignature.php
deleted file mode 100644
index f2725ce4..00000000
--- a/samples/rest/notifications/VerifyWebhookSignature.php
+++ /dev/null
@@ -1,32 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$headers =array(
-    'auth_algo' => 'SHA256withRSA',          // The algorithm that PayPal uses to generate the signature and that you can use to verify the signature. Extract this value from the PAYPAL-AUTH-ALGO response header, which is received with the webhook notification.
-    'cert_url' => 'https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-1d93a270',           // The X.509 public key certificate. Download the certificate from this URL and use it to verify the signature. Extract this value from the PAYPAL-CERT-URL response header, which is received with the webhook notification.
-    'transmission_id' => '28559930-7bbb-11e9-9556-0b8753ae570e',    // The ID of the HTTP transmission. Contained in the PAYPAL-TRANSMISSION-ID header of the notification message.
-    'transmission_sig' => 'UyGFLQPLgB/ucPt8pRXq9+69NKA8X9x7BNJCNgM9ei2zyPnPgE/higerPvpmD/J/VWFtpcLFUPe3WPh9X5Amr4uBbFR3mG1rR8E4jK43adAk9+Pcx9CAazykMwJ/VZYsUMgyGPMhRUofbrtI7sLclh+OULCFMz23wd04TJItYS/n+slkOfmUtqc4+5RVzNqsA1HYaKwZ3eZi6pRU2WYzsg/CltPLFenqCek6wHAIVOdH0HIBCqUtj2XQjtRBPzDZ6FZtCLnqpZ7MlSRCu0a0eJ7eySb0okDfmdTyfLmgsVdkSSTnNivYMU1f4rc3zUrCcFKSXBeSjHN1sZj5v3sJuw==',
-       // The PayPal-generated asymmetric signature. Appears in the PAYPAL-TRANSMISSION-SIG header of the notification message.
-    'transmission_time' => '2019-05-21T11:25:37Z',  // The date and time of the HTTP transmission, in Internet date and time format. Appears in the PAYPAL-TRANSMISSION-TIME header of the notification message.    
-);
-
-$webhook_id = '43023250MX034900R';               // The ID of the webhook as configured in your Developer Portal account.
-$webhook_event = file_get_contents('php://input');            // A webhook event notification.
-
-$returnArray = $PayPal->VerifyWebhookSignature($headers, $webhook_id,$webhook_content);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/notifications/WebhooksEventTypes.php b/samples/rest/notifications/WebhooksEventTypes.php
deleted file mode 100644
index b299700d..00000000
--- a/samples/rest/notifications/WebhooksEventTypes.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$returnArray = $PayPal->WebhooksEventTypes();
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/payment/AuthorizationCapture.php b/samples/rest/payment/AuthorizationCapture.php
deleted file mode 100755
index 635d2c14..00000000
--- a/samples/rest/payment/AuthorizationCapture.php
+++ /dev/null
@@ -1,25 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId='74403845H58487211';                           // Required. The Authorization ID of the payment.
-$amount = array(
-    'Currency' => 'USD',                                        //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '20.00',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$returnArray = $PayPal->AuthorizationCapture($authorizationId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/AuthorizePaymentUsingPayPal.php b/samples/rest/payment/AuthorizePaymentUsingPayPal.php
deleted file mode 100644
index 0cd84907..00000000
--- a/samples/rest/payment/AuthorizePaymentUsingPayPal.php
+++ /dev/null
@@ -1,100 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='authorize';        //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-
-// ### Notice
-// If your intent is "order" set this as URL array.
-// ReturnUrl=OrderGet.php?success=true
-// CancelUrl=OrderGet.php?success=false
-//
-// ### For execute payment
-// If your intent is "sale" or "authorize" set this as URL array.
-//ReturnUrl=ExecutePayment.php?success=true
-//CancelUrl=ExecutePayment.php?success=false
-
-
-$urls= array(
-    'ReturnUrl'   => 'ExecutePayment.php?success=true',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'ExecutePayment.php?success=false',                                   // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$invoiceNumber='INVC-'.rand(0,1000);
-$ExperienceProfileId = '';                                                                  // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';                               // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                                                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                                     // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',                                // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                                       // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                                    // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                                         // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                    // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                     // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                     // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                          // Amount being charged as gift wrap fee.
-);
-
-$amount = array(
-    'Currency' => 'USD',                                      //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-    'Total'    => '20.00',                                    //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256.
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer
-);
-
-$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/CreateFuturePayment.php b/samples/rest/payment/CreateFuturePayment.php
deleted file mode 100644
index 453d1c89..00000000
--- a/samples/rest/payment/CreateFuturePayment.php
+++ /dev/null
@@ -1,106 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$method = 'paypal';         // Payment method being used. "credit_card" is not available for general use. Valid Values: ["credit_card", "paypal"]
-$intent='authorize';        //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-
-// ### Notice
-// If your intent is "order" set this as URL array.
-// ReturnUrl=OrderGet.php?success=true
-// CancelUrl=OrderGet.php?success=false
-//
-// ### For execute payment
-// If your intent is "sale" or "authorize" set this as URL array.
-//ReturnUrl=ExecutePayment.php?success=true
-//CancelUrl=ExecutePayment.php?success=false
-
-
-$urls= array(
-    'ReturnUrl'   => 'ExecutePayment.php?success=true',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'ExecutePayment.php?success=false',                                   // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                                                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                                     // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',                                // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                                       // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                                    // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                                         // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                    // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                     // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                     // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                          // Amount being charged as gift wrap fee.
-);
-
-$amount = array(
-    'Currency' => 'USD',                                      //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-    'Total'    => '20.00',                                    //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256.
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
- ### Get Refresh Token
-// You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.
-// authorization code from mobile sdk
-
-$authorizationCode = 'EK7_MAKlB4QxW1dWKnvnr_CEdLKnpH3vnGAf155Eg8yO8e_7VaQonsqIbTK9CR7tUsoIN2eCc5raOfaGbZDCT0j6k_BDE8GkyLgk8ulcQyR_3S-fgBzjMzBwNqpj3AALgCVR03zw1iT8HTsxZXp3s2U';
-
-// Client Metadata id from mobile sdk
-// For more information look for PayPal-Client-Metadata-Id in https://developer.paypal.com/docs/api/#authentication--headers
-$clientMetadataId = '123123456';
-
-$requestData = array(
-    'intent'         => $intent,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'authorizationCode' => $authorizationCode,
-    'clientMetadataId' => $clientMetadataId
-);
-
-$returnArray = $PayPal->CreateFuturePayment($method,$requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/CreatePayment.php b/samples/rest/payment/CreatePayment.php
deleted file mode 100755
index bc8935b7..00000000
--- a/samples/rest/payment/CreatePayment.php
+++ /dev/null
@@ -1,108 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-// This is Create Payment with Creditcard.
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='sale';                                                 // Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-$ExperienceProfileId = '';                                      // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';   // free-form field for the use of clients to pass in a message to the payer.
-
-$paymentCard = array(
-    'Type'              => 'visa',                           // Required.  The card type.Possible values: VISA, AMEX, SOLO, JCB, STAR, DELTA, DISCOVER, SWITCH, MAESTRO, CB_NATIONALE, CONFINOGA, COFIDIS, ELECTRON, CETELEM, CHINA_UNION_PAY, MASTERCARD.
-    'Number'            => '4032039334307404',               // Required.  The card number.  No spaces or punctuation.
-    'ExpireMonth'       => '12',                             // Required.  The two-digit expiry month for the card.
-    'ExpireYear'        => '2021',                           // Required.  The four-digit expiry year for the card.
-    'Cvv2'              => '012',                            // Required.  The validation code for the card. Supported for payments but not for saving payment cards for future use.
-    'FirstName'         => 'Test',                           // Required.  The first name of the card holder.
-    'LastName'          => 'Testerson',                      // The last name of the card holder.
-    'BillingCountry'    => 'US',                             // Required. The two-letter country code. For Example 'US'.
-    'StartMonth'        => '',                               // The two-digit start month for the card. Required for UK Maestro cards.
-    'StartYear'         => '',                               // The four-digit start year for the card. Required for UK Maestro cards. 
-    'ExternalCustomerId'=> '',                               // The externally-provided ID of the customer for whom to list credit cards.
-    'Status'            => '',                               // Possible values: EXPIRED, ACTIVE. The state of the funding instrument.
-    'CardProductClass'  => '',                               // Possible values: CREDIT, DEBIT, GIFT, PAYPAL_PREPAID, PREPAID, UNKNOWN. The product class of the financial instrument issuer.
-    'issue_number'      => ''                                // The one- to two-digit card issue number. Required for UK Maestro cards. Maximum length: 2.    
-);
-// billingAddress object with PaymentCard (Optional).
-$billingAddress = array(
-    'line1'        => '3909 Witmer Road',                    // Required.  First street address.
-    'line2'        => 'Niagara Falls',                       // Optional line 2 of the Address
-    'city'         => 'Niagara Falls',                       // Required.  Name of City.    
-    'state'        => 'NY',                                  // Required. 2 letter code for US states, and the equivalent for other countries..
-    'postal_code'  => '14305',                               // Required. postal code of your area.
-    'country_code' => 'US',                                  // 2 letter country code..   
-    'phone'        => '716-298-1822'                         // Required.  Postal code of payer.
-);
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => 'MOBEYHZ2YAXZMF2J',                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Apple iPhone 6 (Space Grey, 16 GB)',   // Item name. 127 characters max.
-    'Description' => 'With a beautiful finish and a light weight',  // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                    // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                 // Item cost. 10 characters max. 
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => '0.3'                                   // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => 'MOBEYHZ2YAXZMF21',                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Apple iPhone 7',                       // Item name. 127 characters max.
-    'Description' => '',                                     // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '5',                                    // Number of a particular item. 10 characters max
-    'Price'       => '2.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => '0.2'                                   // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                   // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                    // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                    // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                         // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => 'USD',                                     //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '20.00',                                   //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                  // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                  // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                  // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                  // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                  // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                  // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                   // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'paymentCard'    => $paymentCard,
-    'billingAddress' => $billingAddress,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer
-);
-
-$returnArray = $PayPal->CreatePayment($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/CreatePaymentUsingPayPal.php b/samples/rest/payment/CreatePaymentUsingPayPal.php
deleted file mode 100755
index 516f4b17..00000000
--- a/samples/rest/payment/CreatePaymentUsingPayPal.php
+++ /dev/null
@@ -1,89 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='authorize';        //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-
-$urls= array(
-    'ReturnUrl'   => 'ExecutePayment.php?success=true',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'ExecutePayment.php?success=false',                                   // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$invoiceNumber='INVC-'.rand(0,1000);
-$ExperienceProfileId = '';                                                                  // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';                               // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                                                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                                     // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',                                // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                                       // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                                    // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                                         // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                    // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                     // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                     // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                          // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => 'USD',                                      //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '20.00',                                    //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,    
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer
-);
-
-$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/CreatePaymentUsingSavedCardVault.php b/samples/rest/payment/CreatePaymentUsingSavedCardVault.php
deleted file mode 100755
index 30d6913d..00000000
--- a/samples/rest/payment/CreatePaymentUsingSavedCardVault.php
+++ /dev/null
@@ -1,73 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='sale';                                           //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.    
-
-$cardID='CARD-8N17066680732224LLRKDUGY';                  // Saved credit card id from vault.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => 'MOBEYHZ2YAXZMF2J',                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Apple iPhone 6 (Space Grey, 16 GB)',// Item name. 127 characters max.    
-    'Quantity'    => '1',                                 // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                              // Item cost. 10 characters max. 
-    'Currency'    => 'USD',                               // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => 'MOBEYHZ2YAXZMF21',                   // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Apple iPhone 7',                     // Item name. 127 characters max.   
-    'Quantity'    => '5',                                  // Number of a particular item. 10 characters max
-    'Price'       => '2.00',                               // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                  // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                   // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                   // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                        // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => 'USD',                                    //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '20.00',                                  //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction
-);
-
-$returnArray = $PayPal->CreatePaymentUsingSavedCardVault($requestData,$cardID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/CreateThirdPartyPayment.php b/samples/rest/payment/CreateThirdPartyPayment.php
deleted file mode 100644
index 9e4c9f64..00000000
--- a/samples/rest/payment/CreateThirdPartyPayment.php
+++ /dev/null
@@ -1,102 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='sale';                                             //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.    
-
-// ### Notice
-// If your intent is "order" set this as URL array.
-// ReturnUrl=OrderGet.php?success=true 
-// CancelUrl=OrderGet.php?success=false
-//
-// ### For execute payment
-// If your intent is "sale" or "authorize" set this as URL array.
-//ReturnUrl=ExecutePayment.php?success=true
-//CancelUrl=ExecutePayment.php?success=false
-
-$third_party_merchant_email = 'paypal-facilitator@angelleye.com';                      // Specify a payee with that user's email or merchant id Merchant Id can be found at https://www.paypal.com/businessprofile/settings/
-
-$urls= array(
-    'ReturnUrl'   => 'ExecutePayment.php?success=true',                                     // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'ExecutePayment.php?success=false',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$invoiceNumber='INVC_'.rand(0,1000);
-$ExperienceProfileId = '';                                   // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';                   // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                  // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',           // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                    // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                  // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                   // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                   // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                        // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => 'USD',                                    //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '20.00',                                  //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,    
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer,
-    'Payee'          => $third_party_merchant_email
-);
-
-$returnArray = $PayPal->CreateThirdPartyPayment($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/ExecutePayment.php b/samples/rest/payment/ExecutePayment.php
deleted file mode 100755
index ae54b0cd..00000000
--- a/samples/rest/payment/ExecutePayment.php
+++ /dev/null
@@ -1,64 +0,0 @@
-/execute'.
-
-$configArray = array(
-    'Sandbox' => $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-// ### Approval Status
-// Determine if the user approved the payment or not
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    $paymentId = $_GET['paymentId'];
-    $payer_id = $_GET['PayerID'];
-
-    // ### Optional Changes to Amount
-    // If you wish to update the amount that you wish to charge the customer,
-    // based on the shipping address or any other reason, you could
-    // do that by passing the transaction object with just `amount` field in it.
-
-    $details = array(
-        'Shipping' => '2.20',
-        'Tax' => '1.30',
-        'HandlingFee' => '',
-        'ShippingDiscount' => '',
-        'Insurance' => '',
-        'GiftWrap' => '',
-        'Fee' => '',
-        'Subtotal' => '17.50'
-    );
-
-
-    $amount = array(
-        'Currency' => 'USD',
-        'Total' => '21.00',
-        'Details' => $details
-    );
-
-    $result = $PayPal->ExecutePayment($paymentId,$payer_id,$amount);
-    echo "
";
-    print_r($result);
-} else {
-    echo "User Cancelled the Approval";
-    exit;
-}
diff --git a/samples/rest/payment/GetAuthorization.php b/samples/rest/payment/GetAuthorization.php
deleted file mode 100755
index 901c814e..00000000
--- a/samples/rest/payment/GetAuthorization.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId='37F85749FN9121741';                  //The Authorization ID of the payment for which to show details.
-
-$returnArray = $PayPal->GetAuthorization($authorizationId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/GetCapture.php b/samples/rest/payment/GetCapture.php
deleted file mode 100755
index ac8faac3..00000000
--- a/samples/rest/payment/GetCapture.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationCaptureId = '89X135566E000560D';                       // Authorization Capture id you get from the Authorization Capture process.
-
-$returnArray = $PayPal->GetCapture($authorizationCaptureId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/ListPayments.php b/samples/rest/payment/ListPayments.php
deleted file mode 100755
index b3d40144..00000000
--- a/samples/rest/payment/ListPayments.php
+++ /dev/null
@@ -1,35 +0,0 @@
- $sandbox,    
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$params = array(
-    'count'       => '',            // Default: 10. The number of items to list in the response.
-    'start_index' => '',            // The ID of the starting resource in the response. When results are paged, you can use the next_id value as the start_id to continue with the next set of results.
-    'start_id'    => '',            // The start index of the resources to return. Typically used to jump to a specific position in the resource history based on its cart. Example for starting at the second item in a list of results: ?start_index=2
-    'start_time'  => '',            // The date and time when the resource was created. Indicates the start of a range of results. Example: start_time=2013-03-06T11:00:00Z
-    'end_time'    => '',            // The date and time when the resource was created. Indicates the end of a range of results. Format: date-time.
-);
-
-$returnArray = $PayPal->ListPayments($params);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/OrderAuthorize.php b/samples/rest/payment/OrderAuthorize.php
deleted file mode 100755
index 1c847cb5..00000000
--- a/samples/rest/payment/OrderAuthorize.php
+++ /dev/null
@@ -1,49 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    /**
-     * execute the payment if you don't know OrderID and only knows payment id and payment state is just created
-     * but if you know Order id then you can directly use $orderId function to authorize the order.
-     */
-
-    $paymentId = $_GET['paymentId'];
-    $payer_id = $_GET['PayerID'];
-
-    $result = $PayPal->ExecutePayment($paymentId,$payer_id);
-    if($result['RESULT'] == 'Success'){
-        $orderId = $result['ORDER']['id'];                               // Replace $orderId with any static Id you might already have.
-
-        $amount = array(
-            'Currency' => 'USD',                                        //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-            'Total'    => '2.00',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-        );
-
-        $returnArray = $PayPal->OrderAuthorize($orderId,$amount);
-        echo "
";
-        print_r($returnArray);
-    }
-    else{
-        echo "
";
-        print_r($result);
-    }
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
-
diff --git a/samples/rest/payment/OrderCapture.php b/samples/rest/payment/OrderCapture.php
deleted file mode 100755
index 85d83339..00000000
--- a/samples/rest/payment/OrderCapture.php
+++ /dev/null
@@ -1,49 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-    /**
-     * execute the payment if you don't know OrderID and only knows payment id and payment state is just created
-     * but if you know Order id then you can directly use $orderId function to capture the order.
-     */
-
-    $paymentId = $_GET['paymentId'];
-    $payer_id = $_GET['PayerID'];
-    $result = $PayPal->ExecutePayment($paymentId,$payer_id);
-
-    if($result['RESULT'] == 'Success'){
-        $orderId = $result['ORDER']['id'];                              // OrderId From Return Object/Array When Created Payment With Paypal/ OrderGet.php
-
-        $amount = array(
-            'Currency' => 'USD',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-            'Total'    => '5.00',                                      //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-        );
-
-        $is_final_capture = true;                                      //  Default is `false`. Indicates whether to release all remaining funds that the authorization holds in the funding instrument. Default is `false`.
-        $returnArray = $PayPal->OrderCapture($orderId,$amount,$is_final_capture);
-        echo "
";
-        print_r($returnArray);
-    }
-    else{
-        echo "
";
-        print_r($result);
-    }
-
-
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
\ No newline at end of file
diff --git a/samples/rest/payment/OrderCreateForAuthorization.php b/samples/rest/payment/OrderCreateForAuthorization.php
deleted file mode 100644
index 630af421..00000000
--- a/samples/rest/payment/OrderCreateForAuthorization.php
+++ /dev/null
@@ -1,89 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='order';                                                                //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-
-$urls= array(
-    'ReturnUrl'   => 'OrderAuthorize.php?success=true',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'OrderAuthorize.php?success=false',                                   // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$invoiceNumber='INVC-'.rand(0,1000);
-$ExperienceProfileId = '';                                                                  // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';                               // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                                                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                                     // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',                                // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                                       // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                                    // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                                         // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                    // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                     // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                     // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                          // Amount being charged as gift wrap fee.
-);
-
-$amount = array(
-    'Currency' => 'USD',                                      //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-    'Total'    => '20.00',                                    //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256.
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer
-);
-
-$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/OrderCreateForCapture.php b/samples/rest/payment/OrderCreateForCapture.php
deleted file mode 100644
index 9e822db3..00000000
--- a/samples/rest/payment/OrderCreateForCapture.php
+++ /dev/null
@@ -1,89 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='order';                                                                //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-
-$urls= array(
-    'ReturnUrl'   => 'OrderCapture.php?success=true',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'OrderCapture.php?success=false',                                   // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$invoiceNumber='INVC-'.rand(0,1000);
-$ExperienceProfileId = '';                                                                  // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';                               // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                                                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                                     // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',                                // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                                       // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                                    // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                                         // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                    // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                     // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                     // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                          // Amount being charged as gift wrap fee.
-);
-
-$amount = array(
-    'Currency' => 'USD',                                      //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-    'Total'    => '20.00',                                    //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256.
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer
-);
-
-$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/OrderCreateForVoid.php b/samples/rest/payment/OrderCreateForVoid.php
deleted file mode 100644
index 1f175b65..00000000
--- a/samples/rest/payment/OrderCreateForVoid.php
+++ /dev/null
@@ -1,89 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='order';                                                                //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.
-
-$urls= array(
-    'ReturnUrl'   => 'OrderDoVoid.php?success=true',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => 'OrderDoVoid.php?success=false',                                   // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => $domain.'samples/rest/payment/'                                     // Required.
-);
-
-$invoiceNumber='INVC-'.rand(0,1000);
-$ExperienceProfileId = '';                                                                  // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = 'Contact us for any questions on your order.';                               // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '123123',                                                  // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Ground Coffee 40 oz',                                     // Item name. 127 characters max.
-    'Description' => 'Medium Roast Single Origin',                                // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '1',                                                       // Number of a particular item. 10 characters max
-    'Price'       => '7.50',                                                    // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                                         // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '321321',                               // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => 'Granola bars',                         // Item name. 127 characters max.
-    'Description' => 'Fruit filled chewy bars.',             // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '2',                                    // Number of a particular item. 10 characters max
-    'Price'       => '5.00',                                 // Item cost. 10 characters max.
-    'Currency'    => 'USD',                                  // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '17.50',                                    // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '1.20',                                     // Amount charged for shipping. 10 characters max with support for 2 decimal places.
-    'Tax'      => '1.30',                                     // Amount charged for tax. 10 characters max with support for 2 decimal places.
-    'GiftWrap' => ''                                          // Amount being charged as gift wrap fee.
-);
-
-$amount = array(
-    'Currency' => 'USD',                                      //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-    'Total'    => '20.00',                                    //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256.
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer
-);
-
-$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/OrderDoVoid.php b/samples/rest/payment/OrderDoVoid.php
deleted file mode 100755
index 290b6dff..00000000
--- a/samples/rest/payment/OrderDoVoid.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    /**
-     * execute the payment if you don't know OrderID and only knows payment id and payment state is just created
-     * but if you know Order id then you can directly use $orderId function to void the order.
-     */
-
-    $paymentId = $_GET['paymentId'];
-    $payer_id = $_GET['PayerID'];
-    $result = $PayPal->ExecutePayment($paymentId,$payer_id);
-
-    if($result['RESULT'] == 'Success'){
-        $orderId = $result['ORDER']['id'];               // OrderId From Return Object/Array When Created Payment With Paypal/ OrderGet.php
-
-        $returnArray = $PayPal->OrderDoVoid($orderId);
-        echo "
";
-        print_r($returnArray);
-    }
-    else{
-        echo "
";
-        print_r($result);
-    }
-
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
diff --git a/samples/rest/payment/OrderGet.php b/samples/rest/payment/OrderGet.php
deleted file mode 100755
index a3c8ccc2..00000000
--- a/samples/rest/payment/OrderGet.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-$order_id = '44565795N60930235'; // Add sale transaction id to see the details of that Order
-
-$result = $PayPal->OrderGet($order_id);
-echo "
";
-print_r($result);
-
diff --git a/samples/rest/payment/Reauthorization.php b/samples/rest/payment/Reauthorization.php
deleted file mode 100644
index f3155e59..00000000
--- a/samples/rest/payment/Reauthorization.php
+++ /dev/null
@@ -1,47 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId = "O-3E566053FX793851D";      // The ID of the authorization to re-authorize.
-
-$amount = array(
-    'Currency' => 'USD',   //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '4.00',  //Required. The total amount charged to the payee by the payer. For refunds, represents the amount that the payee refunds to the original payer. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-    'Details'  => array(
-        'Subtotal' => '',   // The subtotal amount for the items. If the request includes line items, this property is required. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point. 
-        'Shipping' => '',   // The shipping fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'Tax'      => '',    // The tax. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'HandlingFee' => '',   // The handling fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'ShippingDiscount' => '',  // The shipping fee discount. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'Insurance' => '',      // The insurance fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'GiftWrap' => ''       // The gift wrap fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point.   
-    )
-);
-
-
-$returnArray = $PayPal->Reauthorization($authorizationId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/RefundCapture.php b/samples/rest/payment/RefundCapture.php
deleted file mode 100755
index 67f806e3..00000000
--- a/samples/rest/payment/RefundCapture.php
+++ /dev/null
@@ -1,36 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$captureId = '86C113543M927163C';                                                // The ID of the captured payment to refund. AuthorizationCapture.php returns object with CaptureID.
-
-$amount = array(
-    'Currency' => 'USD',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '4.00',                                      //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$refundParameters = array(
-    'Description'   => 'this is desc for refund',                                     // Description of what is being refunded for. Character length and limitations: 255 single-byte alphanumeric characters.
-    'RefundSource'  => '',                                     // Valid Values: ["INSTANT_FUNDING_SOURCE", "ECHECK", "UNRESTRICTED"]. Type of PayPal funding source (balance or eCheck) that can be used for auto refund.
-    'Reason'        => '',                                     // Reason description for the Sale transaction being refunded.
-    'InvoiceNumber' => '',                                     // The invoice number that is used to track this payment. Character length and limitations: 127 single-byte alphanumeric characters.
-    'RefundAdvice'  => ''                                      // Flag to indicate that the buyer was already given store credit for a given transaction.
-);
-
-$returnArray = $PayPal->RefundCapture($captureId,$amount,$refundParameters);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/ShowPaymentDetails.php b/samples/rest/payment/ShowPaymentDetails.php
deleted file mode 100755
index 8d4980fc..00000000
--- a/samples/rest/payment/ShowPaymentDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$PaymentID='PAY-7UY278710A4871533LRVJI6Q';                  //The ID of the payment for which to show details.
-
-$returnArray = $PayPal->ShowPaymentDetails($PaymentID);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/ShowRefundDetails.php b/samples/rest/payment/ShowRefundDetails.php
deleted file mode 100644
index 6e54a0ef..00000000
--- a/samples/rest/payment/ShowRefundDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$refund_id ='8U6965136S7813607';  // The ID of the refund for which to show details.
-
-$returnArray = $PayPal->ShowRefundDetails($refund_id);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/UpdatePayment.php b/samples/rest/payment/UpdatePayment.php
deleted file mode 100644
index 76432978..00000000
--- a/samples/rest/payment/UpdatePayment.php
+++ /dev/null
@@ -1,62 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$paymentId = 'PAY-51939243WX127101ALPG4QZQ';    // The ID of the payment to update.
-
-$patches = array();
-
-$array1 = array(
-    "operation" => "replace",                   // The operation to complete. Possible values: add, remove, replace, move, copy, test.
-    "path" => "/transactions/0/amount",         // The JSON pointer to the target document location at which to complete the operation.
-    "value" => array(                           // number,integer,string,boolean,null,array,object. The value to apply. The remove operation does not require a value.
-
-        'total' => '33.00',
-        'currency' => 'USD',
-        'details' => array(
-            'subtotal' => '17.50',
-            'shipping' => '6.20',
-            'tax' => '9.30'
-        )
-    )
-);
-
-array_push($patches, $array1);
-
-$array2 = array(
-    "operation" => "add",                                       // The operation to complete. Possible values: add, remove, replace, move, copy, test.
-    "path" => "/transactions/0/item_list/shipping_address",     // The JSON pointer to the target document location at which to complete the operation.
-    "value" => array(                                           // number,integer,string,boolean,null,array,object. The value to apply. The remove operation does not require a value.
-        'recipient_name' => 'Gruneberg, Anna',
-        'line1' => '52 N Main St',
-        'city' => 'San Jose',
-        "state" => "CA",
-        "postal_code" => "95112",
-        "country_code" => "US"
-    )
-);
-
-array_push($patches, $array2);
-
-$returnArray = $PayPal->UpdatePayment($paymentId,$patches);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payment/VoidAuthorization.php b/samples/rest/payment/VoidAuthorization.php
deleted file mode 100755
index ea32e286..00000000
--- a/samples/rest/payment/VoidAuthorization.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId = '5A772513EY236593C'; // Replace $authorizationid with any static Id you might already have. It will do a void on it
-
-$returnArray = $PayPal->VoidAuthorization($authorizationId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/paymentexperience/CreateWebProfile.php b/samples/rest/paymentexperience/CreateWebProfile.php
deleted file mode 100755
index fc7f0244..00000000
--- a/samples/rest/paymentexperience/CreateWebProfile.php
+++ /dev/null
@@ -1,56 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$FlowConfig = array(
-    'LandingPageType'     => 'Billing',                          // The type of landing page to display on the PayPal site for user checkout. Set to `Billing` to use the non-PayPal account landing page. Set to `Login` to use the PayPal account login landing page.
-    'BankTxnPendingUrl'   => 'http://www.yeowza.com/',           // The merchant site URL to display after a bank transfer payment. Valid for only the Giropay or bank transfer payment method in Germany.
-    'UserAction'          => 'commit',                           // Defines whether buyers can complete purchases on the PayPal or merchant website.
-    'ReturnUriHttpMethod' => 'GET',                              // Defines the HTTP method to use to redirect the user to a return URL. A valid value is `GET` or `POST`.    
-);
-
-$presentation = array(
-    'BrandName'           => 'AngellEye',                      // A label that overrides the business name in the PayPal account on the PayPal pages. Character length and limitations: 127 single-byte alphanumeric characters.
-    'LogoImage'           => 'https://www.angelleye.com/wp-content/uploads/2015/06/angelleye-logo-159x43.png',                                             // A URL to the logo image. A valid media type is `.gif`, `.jpg`, or `.png`. The maximum width of the image is 190 pixels. The maximum height of the image is 60 pixels. PayPal crops images that are larger. PayPal places your logo image at the top of the cart review area. PayPal recommends that you store the image on a secure (HTTPS) server. Otherwise, web browsers display a message that checkout pages contain non-secure items. Character length and limit: 127 single-byte alphanumeric characters.
-    'LocaleCode'          => 'US',                               // The locale of pages displayed by PayPal payment experience. A valid value is `AU`, `AT`, `BE`, `BR`, `CA`, `CH`, `CN`, `DE`, `ES`, `GB`, `FR`, `IT`, `NL`, `PL`, `PT`, `RU`, or `US`. A 5-character code is also valid for languages in specific countries: `da_DK`, `he_IL`, `id_ID`, `ja_JP`, `no_NO`, `pt_BR`, `ru_RU`, `sv_SE`, `th_TH`, `zh_CN`, `zh_HK`, or `zh_TW`.
-    'ReturnUrlLabel'      => 'Return',                           // A label to use as hypertext for the return to merchant link.
-    'NoteToSellerLabel'   => 'Thanks!',                          // A label to use as the title for the note to seller field. Used only when `allow_note` is `1`.    
-);
-
-$InputFields = array(
-    'AllowNote'           => true,                               // Type bool. Indicates whether the buyer can enter a note to the merchant on the PayPal page during checkout.
-    'NoShipping'          => 1,                                  // Indicates whether PayPal displays shipping address fields on the experience pages. Valid value is `0`, `1`, or `2`. Set to `0` to display the shipping address on the PayPal pages. Set to `1` to redact shipping address fields from the PayPal pages. Set to `2` to not pass the shipping address but instead get it from the buyer's account profile. For digital goods, this field is required and value must be `1`.
-    'AddressOverride'     => 0,                                  // Indicates whether to display the shipping address that is passed to this call rather than the one on file with PayPal for this buyer on the PayPal experience pages. Valid value is `0` or `1`. Set to `0` to display the shipping address on file. Set to `1` to display the shipping address supplied to this call; the buyer cannot edit this shipping address.    
-);
-
-$WebProfile = array(
-    'Name'                => "T-Shirt Shop" . uniqid(),     // The web experience profile name. Unique for a specified merchant's profiles.
-    'Temporary'           => true,                               // Indicates whether the profile persists for three hours or permanently. Set to `false` to persist the profile permanently. Set to `true` to persist the profile for three hours.    
-);
-
-$requestData = array(
-    'FlowConfig'   => $FlowConfig,
-    'presentation' => $presentation,
-    'InputFields'  => $InputFields,
-    'WebProfile'   => $WebProfile
-);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateWebProfile($requestData);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
-
diff --git a/samples/rest/paymentexperience/DeleteWebProfile.php b/samples/rest/paymentexperience/DeleteWebProfile.php
deleted file mode 100755
index efbdd3ea..00000000
--- a/samples/rest/paymentexperience/DeleteWebProfile.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$ProfileID = 'TXP-293865132D411505B';       // Required. The ID of the profile for which to show details.
-
-$returnArray = $PayPal->DeleteWebProfile($ProfileID);
-echo "
";
-var_dump($returnArray);
-
diff --git a/samples/rest/paymentexperience/GetWebProfile.php b/samples/rest/paymentexperience/GetWebProfile.php
deleted file mode 100755
index 43198c6c..00000000
--- a/samples/rest/paymentexperience/GetWebProfile.php
+++ /dev/null
@@ -1,25 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$ProfileID = 'TXP-0Y6000321B436213T';       // Required. The ID of the profile for which to show details.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->GetWebProfile($ProfileID);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
-
diff --git a/samples/rest/paymentexperience/ListWebProfiles.php b/samples/rest/paymentexperience/ListWebProfiles.php
deleted file mode 100755
index 6c0630f4..00000000
--- a/samples/rest/paymentexperience/ListWebProfiles.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->ListWebProfiles();
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
-
diff --git a/samples/rest/paymentexperience/PartiallyUpdateWebProfile.php b/samples/rest/paymentexperience/PartiallyUpdateWebProfile.php
deleted file mode 100755
index 4c818829..00000000
--- a/samples/rest/paymentexperience/PartiallyUpdateWebProfile.php
+++ /dev/null
@@ -1,41 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$profileID = 'TXP-0Y6000321B436213T';                   // Required. The ID of the profile to update.
-
-$patchArray = array();
-
-$array1 = array(
-    'Op'      => 'add',                                 // The operation to perform. Valid Values: ["add", "remove", "replace", "move", "copy", "test"]
-    'Path'    => '/presentation/brand_name',            // A JSON pointer that references a location in the target document where the operation is performed. A `string` value.
-    'Value'   => 'New Brand Name',                      // New value to apply based on the operation.
-);
-array_push($patchArray,$array1);
-
-$array2 = array(
-    'Op'      => 'remove',                               // The operation to perform. Valid Values: ["add", "remove", "replace", "move", "copy", "test"]
-    'Path'    => '/flow_config/landing_page_type',       // A JSON pointer that references a location in the target document where the operation is performed. A `string` value.
-    'Value'   => '',                                     // New value to apply based on the operation.
-);
-array_push($patchArray,$array2);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->PartiallyUpdateWebProfile($patchArray,$profileID);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
-
diff --git a/samples/rest/paymentexperience/UpdateWebProfile.php b/samples/rest/paymentexperience/UpdateWebProfile.php
deleted file mode 100755
index eae05212..00000000
--- a/samples/rest/paymentexperience/UpdateWebProfile.php
+++ /dev/null
@@ -1,58 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$profileID = 'TXP-0Y6000321B436213T';                                        //Required. The ID of the profile to update.
-
-$FlowConfig = array(
-    'LandingPageType'     => 'Billing',                                      // The type of landing page to display on the PayPal site for user checkout. Set to `Billing` to use the non-PayPal account landing page. Set to `Login` to use the PayPal account login landing page.
-    'BankTxnPendingUrl'   => '',                                             // The merchant site URL to display after a bank transfer payment. Valid for only the Giropay or bank transfer payment method in Germany.
-    'UserAction'          => '',                                             // Defines whether buyers can complete purchases on the PayPal or merchant website.
-    'ReturnUriHttpMethod' => '',                                             // Defines the HTTP method to use to redirect the user to a return URL. A valid value is `GET` or `POST`.    
-);
-
-$presentation = array(
-    'BrandName'           => 'AngellEye Paypal',                               // A label that overrides the business name in the PayPal account on the PayPal pages. Character length and limitations: 127 single-byte alphanumeric characters.
-    'LogoImage'           => '',                                             // A URL to the logo image. A valid media type is `.gif`, `.jpg`, or `.png`. The maximum width of the image is 190 pixels. The maximum height of the image is 60 pixels. PayPal crops images that are larger. PayPal places your logo image at the top of the cart review area. PayPal recommends that you store the image on a secure (HTTPS) server. Otherwise, web browsers display a message that checkout pages contain non-secure items. Character length and limit: 127 single-byte alphanumeric characters.
-    'LocaleCode'          => '',                                             // The locale of pages displayed by PayPal payment experience. A valid value is `AU`, `AT`, `BE`, `BR`, `CA`, `CH`, `CN`, `DE`, `ES`, `GB`, `FR`, `IT`, `NL`, `PL`, `PT`, `RU`, or `US`. A 5-character code is also valid for languages in specific countries: `da_DK`, `he_IL`, `id_ID`, `ja_JP`, `no_NO`, `pt_BR`, `ru_RU`, `sv_SE`, `th_TH`, `zh_CN`, `zh_HK`, or `zh_TW`.
-    'ReturnUrlLabel'      => '',                                             // A label to use as hypertext for the return to merchant link.
-    'NoteToSellerLabel'   => '',                                             // A label to use as the title for the note to seller field. Used only when `allow_note` is `1`.    
-);
-
-$InputFields = array(
-    'AllowNote'           => '',                                             // Type bool. Indicates whether the buyer can enter a note to the merchant on the PayPal page during checkout.
-    'NoShipping'          => '',                                             // Indicates whether PayPal displays shipping address fields on the experience pages. Valid value is `0`, `1`, or `2`. Set to `0` to display the shipping address on the PayPal pages. Set to `1` to redact shipping address fields from the PayPal pages. Set to `2` to not pass the shipping address but instead get it from the buyer's account profile. For digital goods, this field is required and value must be `1`.
-    'AddressOverride'     => '',                                             // Indicates whether to display the shipping address that is passed to this call rather than the one on file with PayPal for this buyer on the PayPal experience pages. Valid value is `0` or `1`. Set to `0` to display the shipping address on file. Set to `1` to display the shipping address supplied to this call; the buyer cannot edit this shipping address.    
-);
-
-$WebProfile = array(
-    'Name'                => "AngellEye T-Shirt Shop" . uniqid(),                 // Required. | The web experience profile name. Unique for a specified merchant's profiles.
-    'Temporary'           => '',                                             // Indicates whether the profile persists for three hours or permanently. Set to `false` to persist the profile permanently. Set to `true` to persist the profile for three hours.    
-);
-
-$requestData = array(
-    'FlowConfig'   => $FlowConfig,
-    'presentation' => $presentation,
-    'InputFields'  => $InputFields,
-    'WebProfile'   => $WebProfile
-);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->UpdateWebProfile($requestData,$profileID);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-var_dump($PayPalResult);
-
diff --git a/samples/rest/payouts/CancelPayoutItem.php b/samples/rest/payouts/CancelPayoutItem.php
deleted file mode 100755
index 4dbe353f..00000000
--- a/samples/rest/payouts/CancelPayoutItem.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-//## Payout Item ID you get when you create Mass payment single/batch.
-
-$payoutItemId='8NBP6Q535GXUL';                  // Required. The ID of the Payout Item for which to show details.
-
-$returnArray = $PayPal->CancelPayoutItem($payoutItemId);
-echo "
";
-print_r($returnArray);
diff --git a/samples/rest/payouts/CreateBatchPayout.php b/samples/rest/payouts/CreateBatchPayout.php
deleted file mode 100755
index 7b50ff52..00000000
--- a/samples/rest/payouts/CreateBatchPayout.php
+++ /dev/null
@@ -1,76 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-$batchHeader = array(
-    'SenderBatchId' => uniqid(),                                   // A sender-specified ID number. Tracks the batch payout in an accounting system.Note: PayPal prevents duplicate batches from being processed. If you specify a `sender_batch_id` that was used in the last 30 days, the API rejects the request and returns an error message that indicates the duplicate `sender_batch_id` and includes a HATEOAS link to the original batch payout with the same `sender_batch_id`. If you receive a HTTP `5nn` status code, you can safely retry the request with the same `sender_batch_id`. In any case, the API completes a payment only once for a specific `sender_batch_id` that is used within 30 days.
-    'EmailSubject'  => 'AngellEye : You have a Payout!',           // The subject line text for the email that PayPal sends when a payout item completes. The subject line is the same for all recipients. Value is an alphanumeric string with a maximum length of 255 single-byte characters.
-);
-
-$PayoutItem = array();
-
-$PayoutItem1 = array(
-    //  ### RecipientType 
-    //  Valid values: EMAIL | PHONE | PAYPAL_ID. 
-    //  The type of ID that identifies the payment receiver.
-    //  EMAIL. Unencrypted email. Value is a string of up to 127 single-byte characters.
-    //  PHONE. Unencrypted phone number.
-    //  Note: The PayPal sandbox does not support the PHONE recipient type.
-    //  PAYPAL_ID Encrypted PayPal account number.
-    
-    'RecipientType' => 'EMAIL',                                    // Valid values: EMAIL | PHONE | PAYPAL_ID.      
-    'Note'          => 'Thanks for your patronage!',               // Optional. A sender-specified note for notifications. Value is any string value. Maximum length: 4000.
-    'Receiver'      => 'paypal-buyer@angelleye.com',               // The receiver of the payment. Corresponds to the recipient_type value in the request. Maximum length: 127.
-    'SenderItemId'  => uniqid(),                                   // A sender-specified ID number. Tracks the batch payout in an accounting system. Maximum length: 30.
-    'Amount' => array(
-        'currency' => 'USD',                                            // Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-        'value'    => '4.00',                                           // Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-    )
-);
-
-array_push($PayoutItem, $PayoutItem1);
-
-$PayoutItem2 = array(
-    //  ### RecipientType 
-    //  Valid values: EMAIL | PHONE | PAYPAL_ID. 
-    //  The type of ID that identifies the payment receiver.
-    //  EMAIL. Unencrypted email. Value is a string of up to 127 single-byte characters.
-    //  PHONE. Unencrypted phone number.
-    //  Note: The PayPal sandbox does not support the PHONE recipient type.
-    //  PAYPAL_ID Encrypted PayPal account number.
-    
-    'RecipientType' => 'EMAIL',                                 // Valid values: EMAIL | PHONE | PAYPAL_ID.      
-    'Note'          => 'Thanks for your patronage!',         // Optional. A sender-specified note for notifications. Value is any string value. Maximum length: 4000.
-    'Receiver'      => 'kiritpatel571989-buyer@ymail.com',      // The receiver of the payment. Corresponds to the recipient_type value in the request. Maximum length: 127.
-    'SenderItemId'  => uniqid(),                                // A sender-specified ID number. Tracks the batch payout in an accounting system. Maximum length: 30.
-    'Amount' => array(
-        'currency' => 'USD',                                            // Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies.
-        'value'    => '14.00',                                           // Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-    )
-);
-
-array_push($PayoutItem, $PayoutItem2);
-
-$requestData=array(    
-    "batchHeader" => $batchHeader,
-    "PayoutItem"  => $PayoutItem
-);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateBatchPayout($requestData);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/payouts/CreateSinglePayout.php b/samples/rest/payouts/CreateSinglePayout.php
deleted file mode 100755
index ff804af7..00000000
--- a/samples/rest/payouts/CreateSinglePayout.php
+++ /dev/null
@@ -1,53 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-$batchHeader = array(
-    'SenderBatchId' => uniqid(),                                   // A sender-specified ID number. Tracks the batch payout in an accounting system.Note: PayPal prevents duplicate batches from being processed. If you specify a `sender_batch_id` that was used in the last 30 days, the API rejects the request and returns an error message that indicates the duplicate `sender_batch_id` and includes a HATEOAS link to the original batch payout with the same `sender_batch_id`. If you receive a HTTP `5nn` status code, you can safely retry the request with the same `sender_batch_id`. In any case, the API completes a payment only once for a specific `sender_batch_id` that is used within 30 days.
-    'EmailSubject'  => 'AngellEye : You have a Payout!',          // The subject line text for the email that PayPal sends when a payout item completes. The subject line is the same for all recipients. Value is an alphanumeric string with a maximum length of 255 single-byte characters.
-);
-
-$amount = array(
-    'currency' => 'USD',                                    // Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'value'    => '4.00',                                   // Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places.
-);
-
-$PayoutItem = array(
-    //  ### RecipientType 
-    //  Valid values: EMAIL | PHONE | PAYPAL_ID. 
-    //  The type of ID that identifies the payment receiver.
-    //  EMAIL. Unencrypted email. Value is a string of up to 127 single-byte characters.
-    //  PHONE. Unencrypted phone number.
-    //  Note: The PayPal sandbox does not support the PHONE recipient type.
-    //  PAYPAL_ID Encrypted PayPal account number.
-    
-    'RecipientType' => 'EMAIL',                                 // Valid values: EMAIL | PHONE | PAYPAL_ID.      
-    'Note'          => 'Thanks for your patronage!',            // Optional. A sender-specified note for notifications. Value is any string value. Maximum length: 4000.
-    'Receiver'      => 'paypal-buyer@angelleye.com',            // The receiver of the payment. Corresponds to the recipient_type value in the request. Maximum length: 127.
-    'SenderItemId'  => '2014031400023',                         // A sender-specified ID number. Tracks the batch payout in an accounting system. Maximum length: 30.    
-);
-
-$requestData=array(    
-    "batchHeader" => $batchHeader,
-    "amount"      => $amount,
-    "PayoutItem"  => $PayoutItem
-);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateSinglePayout($requestData);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/payouts/GetPayoutBatchStatus.php b/samples/rest/payouts/GetPayoutBatchStatus.php
deleted file mode 100755
index 5ec2b04d..00000000
--- a/samples/rest/payouts/GetPayoutBatchStatus.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-//## Payout Batch ID you get when you create Mass payment single/batch.
-
-$payoutBatchId='QY89V9W4VBSQ4';                  // Required. The ID of the payout batch for which to show details.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->GetPayoutBatchStatus($payoutBatchId);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/payouts/GetPayoutItemStatus.php b/samples/rest/payouts/GetPayoutItemStatus.php
deleted file mode 100755
index d0676861..00000000
--- a/samples/rest/payouts/GetPayoutItemStatus.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-//## Payout Item ID you get when you create Mass payment single/batch.
-
-$payoutItemId='CV28ACVYTVXGE';                  // Required. The ID of the Payout Item for which to show details.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->GetPayoutItemStatus($payoutItemId);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/paypal_sync/PaypalSyncTransactions.php b/samples/rest/paypal_sync/PaypalSyncTransactions.php
deleted file mode 100644
index 0e3ecefc..00000000
--- a/samples/rest/paypal_sync/PaypalSyncTransactions.php
+++ /dev/null
@@ -1,43 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paypal_sync\PayPalSyncAPI($configArray);
-
-$parameters = array(
-    'transaction_id' => '61K22761BD5574252',                // Filters the transactions in the response by a PayPal transaction ID. A valid transaction ID is 17 characters long, except for an order ID, which is 19 characters long. Minimum length: 17.Maximum length: 19.
-    'transaction_type' => '',                               // Filters the transactions in the response by a PayPal transaction event code. See Transaction event codes. https://developer.paypal.com/docs/integration/direct/sync/transaction-event-codes/
-    'transaction_status' => '',                             // Filters the transactions in the response by a PayPal transaction status code. Value is: 
-                                                            // D : PayPal or merchant rules denied the transaction.
-                                                            // F : The original recipient partially refunded the transaction.
-                                                            // P : The transaction is pending. The transaction was created but waits for another payment process to complete, such as an ACH transaction, before the status changes to S.
-                                                            // S : The transaction successfully completed without a denial and after any pending statuses.
-                                                            // V : A successful transaction was reversed and funds were refunded to the original sender.
-    'transaction_amount' => '',                             // Filters the transactions in the response by a gross transaction amount range. Specify the range as  TO , where  is the lower limit of the gross PayPal transaction amount and  is the upper limit of the gross transaction amount. Specify the amounts in lower denominations. For example, to search for transactions from $5.00 to $10.05, specify [500 TO 1005].
-    'transaction_currency' => '',                           // PayPal transaction currency.
-    'start_date' => '2018-03-01T00:00:00-0700',             // Example : 2017-07-01T00:00:00-0700 Filters the transactions in the response by a start date and time Minimum length: 20.Maximum length: 64. 
-    'end_date' => '2018-03-30T00:00:00-0700',               // Example : 2017-07-30T00:00:00-0700 Filters the transactions in the response by a end date and time Minimum length: 20.Maximum length: 64. 
-    'payment_instrument_type' => '',                        // CREDITCARD | DEBITCARD | Filters the transactions in the response by a payment instrument type, If you omit this parameter, the API does not apply this filter.
-    'store_id'  => '' ,                                     // Filters the transactions in the response by a store ID.
-    'terminal_id' => '',                                    // Filters the transactions in the response by a terminal ID.
-    'fields' => 'all',                                      // Indicates which fields appear in the response. Value is a single field or a comma-separated list of fields. Other fields are : transaction_info | payer_info | shipping_info | auction_info | cart_info | incentive_info | store_info
-    'balance_affecting_records_only' =>  'Y',               // Indicates whether the response includes only balance-impacting transactions or all transactions. Value is either: Y. The default. The response includes only balance transactions. N. The response includes all transactions.
-    'page_size' => '',                                      // Minimum value: 1.  Maximum value: 500. The number of items to return in the response.   
-    'page' => ''                                            // Minimum value: 1. Maximum value: 2147483647.                
-);
-
-$response = $PayPal->PaypalSyncTransactions($parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/samples/rest/referenced_payouts/CreateReferencedBatchPayout.php b/samples/rest/referenced_payouts/CreateReferencedBatchPayout.php
deleted file mode 100644
index 60719886..00000000
--- a/samples/rest/referenced_payouts/CreateReferencedBatchPayout.php
+++ /dev/null
@@ -1,102 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\referenced_payouts\ReferencedPayoutsAPI($configArray);
-
-// Header parameters
-$PayPal_Partner_Attribution_Id = ''; // For more information about PayPal-Partner-Attribution-Id, see https://developer.paypal.com/docs/api/overview/#paypal-partner-attribution-id
-
-/*  Indicates how the client expects the server to process this request.
- *  To process the request asynchronously, set this header to respond-async.
- *  If you omit this header, the API processes the request synchronously.
- *  For synchronous processing the application may levy additional checks on the number of supported items
- *  in the request and may fail the request if those limits are breached.
- */
-$Prefer = '';
-$PayPal_Request_Id = 'idempotent1234';          // The server stores keys for three days. For more information about PayPal-Request-Id, see https://developer.paypal.com/docs/api/overview/#paypal-request-id
-
-if(!empty($PayPal_Partner_Attribution_Id)) {
-    $PayPal->set_partner_attribution_id($PayPal_Partner_Attribution_Id);
-}
-if(!empty($Prefer)) {
-    $PayPal->set_prefer($Prefer);
-}
-if(!empty($PayPal_Request_Id)) {
-    $PayPal->set_paypal_request_id($PayPal_Request_Id);
-}
-
-$referenced_payouts_items = array();
-
-$processing_state_1 = array(
-    'status' => '',         // PENDING | PROCESSING | SUCCESS | FAILED | PAYOUT_FAILED | The item status.
-    'reason' => ''          // INTERNAL_ERROR | NOT_ENOUGH_BALANCE | AMOUNT_CHECK_FAILED | MERCHANT_PARTNER_PERMISSIONS_ISSUE | MERCHANT_RESTRICTIONS | TRANSACTION_UNDER_DISPUTE |TRANSACTION_NOT_VALID | UNSUPPORTED_CURRENCY |PAYOUT_INITIATED | The reason code.
-);
-
-$payout_amount = array(
-    'currency_code' => '',  // The three-character ISO-4217 currency code that identifies the currency.
-    'value' => ''           // Maximum length: 32. | Pattern: ^((-?[0-9]+)|(-?([0-9]+)?[.][0-9]+))$
-);
-
-$referenced_payouts_item_1 = array(
-    'item_id' => '',                        // The ID for the payout item request.
-    'processing_state' => array_filter($processing_state_1),               // The processing state of the reference payout.
-    'reference_id' => '1E9779735S6556259',                   // The original reference ID, based on reference_type, based on the type payout.
-    'reference_type' => 'TRANSACTION_ID',                 // TRANSACTION_ID | OTHERS | The reference type.
-    'payout_transaction_id' => '',          // The encrypted PayPal transaction ID for the payout when the item_status is success.
-    'disbursement_transaction_id' => '',    // The encrypted PayPal transaction ID for the disbursement when the money is moved from settlement hold to receiver.
-    'external_merchant_id' => '',           // The unique ID for the merchant on the partner side. Can be used to retrieve the PayPal account linked to this ID for the payout.
-    'external_reference_id' => '',          // The unique ID for the request on the partner side to enable idempotency. If this parameter is not available, idempotency is enabled for this item.
-    'payee_email' => '',                    // The PayPal merchant account email that receives the payout. Can be used to override the default behavior where the payout receiver is derived from the reference that is passed.
-    'payout_amount' => array_filter($payout_amount),      // The amount to be paid to merchant. 
-    'payout_destination' => '',             // The encrypted PayPal account number or the ID of the financial instrument that received the payout.
-    'invoice_id' => '',                     // The partner invoice ID for this referenced-payouts item. Used for reporting purposes only.
-    'custom' =>''                           // The partner custom data for this referenced-payouts item. Used for reporting purposes only.
-);
-
-array_push($referenced_payouts_items, array_filter($referenced_payouts_item_1));
-
-$referenced_payouts_item_2 = array(
-    'item_id' => '',                        // The ID for the payout item request.
-    'processing_state' => array_filter($processing_state_1),               // The processing state of the reference payout.
-    'reference_id' => '76F40949RG330734X',                   // The original reference ID, based on reference_type, based on the type payout.
-    'reference_type' => 'TRANSACTION_ID',                 // TRANSACTION_ID | OTHERS | The reference type.
-    'payout_transaction_id' => '',          // The encrypted PayPal transaction ID for the payout when the item_status is success.
-    'disbursement_transaction_id' => '',    // The encrypted PayPal transaction ID for the disbursement when the money is moved from settlement hold to receiver.
-    'external_merchant_id' => '',           // The unique ID for the merchant on the partner side. Can be used to retrieve the PayPal account linked to this ID for the payout.
-    'external_reference_id' => '',          // The unique ID for the request on the partner side to enable idempotency. If this parameter is not available, idempotency is enabled for this item.
-    'payee_email' => '',                    // The PayPal merchant account email that receives the payout. Can be used to override the default behavior where the payout receiver is derived from the reference that is passed.
-    'payout_amount' => array_filter($payout_amount),      // The amount to be paid to merchant. 
-    'payout_destination' => '',             // The encrypted PayPal account number or the ID of the financial instrument that received the payout.
-    'invoice_id' => '',                     // The partner invoice ID for this referenced-payouts item. Used for reporting purposes only.
-    'custom' =>''                           // The partner custom data for this referenced-payouts item. Used for reporting purposes only.
-);
-
-array_push($referenced_payouts_items, array_filter($referenced_payouts_item_2));
-
-$referenced_payouts  = $referenced_payouts_items;
-
-$payout_directive = array(
-    'financial_instrument_id' => ''              // Minimum length: 1. Maximum length: 255. The PayPal-provided ID of the financial instrument that receives the payout. If you omit this value, the payout is made to the receiver's balance by default. If you include payee_email to override the original receiver on the individual item or items, the API ignores this field.
-);
-
-$parameters = array(    
-    'referenced_payouts' => $referenced_payouts,         // An array of referenced payouts items. For synchronous execution, the maximum number of items is 10. If you include more than 10 items, the request is processed asynchronously no matter what the partner defined in the Prefer request header.
-    'payout_directive' => array_filter($payout_directive)              // The payout directive. Defines how the payout is made following the referenced payouts, if required. If you include this directive, all items in the request must be for the same original receiver. Otherwise, the request fails. You can override the payout directive at the item level to a different funding instrument, if required.
-);
-
-$response = $PayPal->CreateReferencedBatchPayout($parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/samples/rest/sale/GetSale.php b/samples/rest/sale/GetSale.php
deleted file mode 100644
index 564720d4..00000000
--- a/samples/rest/sale/GetSale.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$sale_id = '999591836N183032D'; // The ID of the sale for which to show details.
-
-$returnArray = $PayPal->GetSale($sale_id);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/sale/RefundSale.php b/samples/rest/sale/RefundSale.php
deleted file mode 100644
index 941ffa18..00000000
--- a/samples/rest/sale/RefundSale.php
+++ /dev/null
@@ -1,46 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$sale_id = '9SS01680HD336413P';         // The ID of the sale transaction to refund.
-
-$amount = array(
-    'Currency' => 'USD',                //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '4.00',               //Required. The total amount charged to the payee by the payer. For refunds, represents the amount that the payee refunds to the original payer. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-    'Details'  => array(
-        'Subtotal' => '',               // The subtotal amount for the items. If the request includes line items, this property is required. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point. 
-        'Shipping' => '',               // The shipping fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'Tax'      => '',               // The tax. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'HandlingFee' => '',            // The handling fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'ShippingDiscount' => '',       // The shipping fee discount. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'Insurance' => '',              // The insurance fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'GiftWrap' => ''                // The gift wrap fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point.   
-    )
-);
-
-$refundParameters = array(
-    'Description'   => 'Refund for double charge.',            // The refund description. Value is a string of single-byte alphanumeric characters. Maximum length: 255.
-    'Reason'        => '',                                     // The refund reason description. Maximum length: 30.
-    'InvoiceNumber' => '',                                     // The invoice number that tracks this payment. Value is a string of single-byte alphanumeric characters. Maximum length: 127.
-);
-
-$returnArray = $PayPal->RefundSale($sale_id,$amount,$refundParameters);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/samples/rest/vault/DeleteCreditCard.php b/samples/rest/vault/DeleteCreditCard.php
deleted file mode 100755
index 74abe113..00000000
--- a/samples/rest/vault/DeleteCreditCard.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$requestData=array(
-                'credit_card_id' => 'CARD-9FH23910JJ6738040LORBJBQ'             //Required.The credit_card_id is the ID of the stored credit card. 
-            );
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->DeleteCreditCard($requestData);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-echo " 
Return '1' on successfull delete, else it will show appropriate error message
"; -print_r($PayPalResult); diff --git a/samples/rest/vault/GetCardDetails.php b/samples/rest/vault/GetCardDetails.php deleted file mode 100644 index 6fa44933..00000000 --- a/samples/rest/vault/GetCardDetails.php +++ /dev/null @@ -1,26 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray); - -$requestData=array( - 'credit_card_id' => 'CARD-42R75882CU076915WLOQMBHQ' // Required. The credit_card_id is the ID of the stored credit card. - ); - -// Pass data into class for processing with PayPal and load the response array into $PayPalResult -$PayPalResult = $PayPal->GetCardDetails($requestData); - -// Write the contents of the response array to the screen for demo purposes. -echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/vault/ListCreditCards.php b/samples/rest/vault/ListCreditCards.php
deleted file mode 100755
index 9612f16f..00000000
--- a/samples/rest/vault/ListCreditCards.php
+++ /dev/null
@@ -1,34 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$requestData=array(
-                'sort_by' => 'create_time',             //Default is create_time. Sorts the vaulted credit cards in the response by either create_time or update_time.      
-                'sort_order' => 'desc',                 //Default: desc.Value is asc for ascending order or desc for descending order.
-                'merchant_id' => '',                    // Filtering by MerchantId set during CreateCreditCard.
-                'page_size'  => '',                     //Default: 10. The number of vaulted credit cards to return in the response beginning with the specified   
-                'page'=>'',                             //Default: 1. A zero-relative index of the list of vaulted credit cards.
-                'start_time' =>'',                      //For example, 2016-11-05T13:15:30Z. Filters the vaulted credit cards in the response to those created on.  
-                'end_time' => ''  ,                     //Filters the vaulted credit cards in the response to those created on or after the start_time date and time and on or before this value 
-                'external_card_id'=>'',                 //Filters the vaulted credit cards in the response to those associated with this bank account ID, which is the facilitator-provided ID of the bank account
-                'external_customer_id'=>'',             //Filters the vaulted credit cards in the response to those associated with this externally-provided customer ID.
-                'total_required'=>''                    //Default true.Indicates whether the response returns the total_items and total_pages values.
-            );
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->ListCreditCards($requestData);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/vault/StoreCreditCard.php b/samples/rest/vault/StoreCreditCard.php
deleted file mode 100644
index 89d04982..00000000
--- a/samples/rest/vault/StoreCreditCard.php
+++ /dev/null
@@ -1,58 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$creditCard = array(
-    'Type' => 'visa',                           // Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-    'Number' => '4111111111111111',             // Required.  Credit card number.  No spaces or punctuation.  
-    'ExpireMonth' => '11',                      // Required.  Credit card expiration Month.  Format is MM
-    'ExpireYear' => '2019',                     // Required.  Credit card expiration year.  Format is YYYY
-    'Cvv2' => '012',                            // Requirements determined by your PayPal account settings.  Security digits for credit card.                                     
-);
-
-$payerInfo = array(
-    'FirstName' => 'Joe',                       // Required.  Payer's first name.
-    'LastName' => 'Shopper'                     // Required.  Payer's last name.
-);
-
-$billingAddress = array(
-    'line1' => '52 N Main ST',                  // Required.  First street address.
-    'line2' => '',                              // Optional line 2 of the Address
-    'city' => 'Johnstown',                      // Required.  Name of City.    
-    'state' => 'OH',                            // Required. 2 letter code for US states, and the equivalent for other countries..
-    'postal_code' => '43210',                   // Required. postal code of your area.
-    'country_code' => 'US',                     // 2 letter country code..   
-    'phone' => '408-334-8890',                  // Required.  Postal code of payer.
-);
-
-$optionalArray = array(
-    'MerchantId'=>'',                           //The ID of the merchant for whom to list credit cards.
-    'ExternalCustomerId'=>'',                   //The externally-provided ID of the customer for whom to list credit cards.
-    'ExternalCardId'=>''                        //The externally-provided ID of the credit card.
-);
-
-$requestData = array(
-    'creditCard' => $creditCard,
-    'payerInfo' => $payerInfo,
-    'billingAddress' => $billingAddress,
-    'optionalArray' =>$optionalArray
-);
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->StoreCreditCard($requestData);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/samples/rest/vault/UpdateCreditCard.php b/samples/rest/vault/UpdateCreditCard.php
deleted file mode 100755
index 11730066..00000000
--- a/samples/rest/vault/UpdateCreditCard.php
+++ /dev/null
@@ -1,88 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-$credit_card_id='CARD-0RN52408SM961693DLCOBNXA';             //Required.The credit_card_id is the ID of the stored credit card. 
-
-$requestData = array(
-    array(
-        'operation' => '',                                   //Valid Values: ["add", "remove", "replace", test"]
-        'path'      => 'type',                               //Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-        'value'     => ''                                    //Value to add/remove/replace/move/copy/test
-    ),
-    array(
-        'operation' => '',                                   //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'number',                             // Required.  Credit card number.  No spaces or punctuation.  
-        'value'     => ''                                    //Value to add/remove/replace/move/copy/test
-    ),    
-    array(
-        'operation' => 'replace',                            //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'expire_month',                       //Required.  Credit card expiration Month.  Format is MM 
-        'value'     => '11'                                  //Value to add/remove/replace/move/copy/test
-    ), 
-    array(
-        'operation' => 'replace',                            //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'expire_year',                        // Required.  Credit card expiration year.  Format is YYYY
-        'value'     => '2029'                                //Value to add/remove/replace/move/copy/test
-    ),     
-    array(
-        'operation' => '',                                   //Valid Values: ["add", "remove", "replace",  "test"]
-        'path'      => 'cvv2',                               // Requirements determined by your PayPal account settings.  Security digits for credit card.                                     
-        'value'     => ''                                    //Value to add/remove/replace/move/copy/test
-    ),         
-    array(
-        'operation' => 'replace',                            //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'first_name',                         //Required.  Payer's first name.
-        'value'     => 'TJ'                                  //Value to add/remove/replace/move/copy/test
-    ),  
-    array(
-        'operation' => 'replace',                            //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'last_name',                          // Required.  Payer's last name.
-        'value'     => 'Mehta'                               //Value to add/remove/replace/move/copy/test
-    ),  
-    array(
-        'operation' => 'remove',                             //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'merchant_id',                        //The ID of the merchant for whom to list credit cards.
-        'value'     => ''                                    //Value to add/remove/replace/move/copy/test
-    ),      
-    array(
-        'operation' => 'add',                                //Valid Values: ["add", "remove", "replace","test"]
-        'path'      => 'external_customer_id',               //The externally-provided ID of the customer for whom to list credit cards.
-        'value'     => ''                                    //Value to add/remove/replace/move/copy/test
-    ),      
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace","test"]
-        'path'      => 'external_card_id',                  //The externally-provided ID of the credit card.
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace","test"]
-        'path'      => 'billing_address',                   //The externally-provided ID of the credit card.
-        'value'     => array(
-                            'line1' => '52 N. Main St.',    // Required.  First street address.
-                            'line2' => '',                  // Optional line 2 of the Address
-                            'city'  => 'Johnstown',         // Required.  Name of City.    
-                            'state' => 'OH',                // Required. 2 letter code for US states, and the equivalent for other countries..
-                            'postal_code' => '43210',       // Required. postal code of your area.
-                            'country_code' => 'US',         // 2 letter country code..   
-                            'phone' => '9989988792',        // Required.  Postal code of payer.
-                        )                          
-    )
-);
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->UpdateCreditCard($requestData,$credit_card_id);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/rest/billing/BillingAPI.php b/src/angelleye/PayPal/rest/billing/BillingAPI.php
deleted file mode 100755
index 4e0dc2d1..00000000
--- a/src/angelleye/PayPal/rest/billing/BillingAPI.php
+++ /dev/null
@@ -1,564 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use PayPal\Api\Agreement;
-use PayPal\Api\AgreementStateDescriptor;
-use PayPal\Api\ChargeModel;
-use PayPal\Api\CreditCard;
-use PayPal\Api\Currency;
-use PayPal\Api\FundingInstrument;
-use PayPal\Api\MerchantPreferences;
-use PayPal\Api\PaymentDefinition;
-use PayPal\Api\Payer;
-use PayPal\Api\PayerInfo;
-use PayPal\Api\Plan;
-use PayPal\Api\Patch;
-use PayPal\Api\PatchRequest;
-use PayPal\Common\PayPalModel;
-use PayPal\Api\ShippingAddress;
-use \angelleye\PayPal\RestClass;
-
-/**
- * BillingAPI.
- * This class is responsible for Billing agreement and plan APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class BillingAPI extends RestClass {    
-        
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-    
-    /**
-     * Creates a billing plan.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function CreatePlan($requestData){
-        try {
-
-            /* Create a new instance of Plan object */
-            $plan = new Plan();
-            if(isset($requestData['plan'])){
-               $this->setArrayToMethods($this->checkEmptyObject($requestData['plan']), $plan);
-            }
-            $paymentDefinitions = array();
-            /** Payment definitions for this billing plan. */
-            if(isset($requestData['paymentDefinitions'])) {
-                $i = 0;
-                foreach ($requestData['paymentDefinitions'] as $pd) {
-                    $paymentDefinition = new PaymentDefinition();
-                    if(isset($pd['Amount'])) {
-                        $pdCurrency = new Currency();
-                        isset($pd['Amount']['value']) ? $pdCurrency->setValue($pd['Amount']['value']) : '';
-                        isset($pd['Amount']['currency']) ? $pdCurrency->setCurrency($pd['Amount']['currency']) : '';
-                        $paymentDefinition->setAmount($pdCurrency);
-                        unset($pd['Amount']);
-                    }
-                    $this->setArrayToMethods($this->checkEmptyObject($pd), $paymentDefinition);
-                    /** Charge Models */
-                    $chargeModels = array();
-                    $j =0;
-                    if(isset($pd['ChargeModels'])){
-                        foreach ($pd['ChargeModels'] as $cm) {
-                            $chargeModel = new ChargeModel();
-                            isset($cm['Type']) ? $chargeModel->setType($cm['Type']) : '';
-                            $cmCurrency = new Currency();
-                            isset($cm['Amount']['value']) ? $cmCurrency->setValue($cm['Amount']['value']) : '';
-                            isset($cm['Amount']['currency']) ? $cmCurrency->setCurrency($cm['Amount']['currency']) : '';
-                            $chargeModel->setAmount($cmCurrency);
-                            $chargeModels[$j] = $chargeModel;
-                            $j++;
-                        }
-                        $paymentDefinition->setChargeModels($chargeModels);
-                    }
-                    $paymentDefinitions[$i] = $paymentDefinition;
-                    $i++;
-                }
-            }
-            $plan->setPaymentDefinitions($paymentDefinitions);
-
-            /** Merchant Preferences */
-            if(isset($requestData['merchant_preferences'])){
-                $merchantPreferences = new MerchantPreferences();
-                $baseUrl = isset($requestData['baseUrl']) ? $requestData['baseUrl'] : '';
-                isset($requestData['ReturnUrl']) ? $merchantPreferences->setReturnUrl($baseUrl.$requestData['ReturnUrl']) : '';
-                isset($requestData['CancelUrl']) ? $merchantPreferences->setCancelUrl($baseUrl.$requestData['CancelUrl']) : '';
-                if(isset($requestData['merchant_preferences']['SetupFee'])) {
-                    $mpCurrency = new Currency();
-                    isset($requestData['merchant_preferences']['SetupFee']['value']) ? $mpCurrency->setValue($requestData['merchant_preferences']['SetupFee']['value']) : '';
-                    isset($requestData['merchant_preferences']['SetupFee']['currency']) ? $mpCurrency->setCurrency($requestData['merchant_preferences']['SetupFee']['currency']) : '';
-                    $merchantPreferences->setSetupFee($mpCurrency);
-                    unset($requestData['merchant_preferences']['SetupFee']);
-                }
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['merchant_preferences']), $merchantPreferences);
-                $plan->setMerchantPreferences($merchantPreferences);
-            }
-
-            $requestArray= clone $plan;
-            $output = $plan->create($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PLAN'] = $output->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for a billing plan, by ID.
-     *
-     * @param string $planId
-     * @return Array|Object
-     */
-    public function GetPlan($planId){
-        try {
-            $plan = Plan::get($planId, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PLAN'] = $plan->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$planId.'}';
-            $returnArray['RAWRESPONSE']=$plan->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Lists billing plans.
-     * To filter the plans that appear in the response, specify one or more optional query and pagination parameters.
-     *
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function ListPlans($parameters){
-            try {
-                $planList = Plan::all(array_filter($parameters), $this->_api_context);                
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['PLANS'] = $planList->toArray();
-                $returnArray['RAWREQUEST']=  json_encode($parameters);
-                $returnArray['RAWRESPONSE']=$planList->toJSON();
-                return $returnArray;                
-            } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-                return $this->createErrorResponse($ex);
-            }        
-    }
-    
-    /**
-     * Updates fields in a billing plan, by ID.
-     *
-     * @param string $planId
-     * @param Array $items
-     * @param string $state
-     * @return Array|Object
-     */
-    public function UpdatePlan($planId,$items,$state){
-        try {
-            
-            $createdPlan = new Plan();
-            $createdPlan->setId($planId);
-
-            $patch = new Patch();
-            $value = new PayPalModel('{
-                       "state":"'.$state.'"
-                     }');
-            $this->setArrayToMethods(array_filter($items), $patch);
-            $patch->setValue($value);                       
-            
-            $patchRequest = new PatchRequest();
-            $patchRequest->addPatch($patch);
-            $requestArray = clone $createdPlan;
-            $createdPlan->update($patchRequest, $this->_api_context);
-            $plan = Plan::get($planId, $this->_api_context);
-                        
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PLAN'] = $plan->toArray();
-            $returnArray['RAWREQUEST'] =$requestArray;
-            $returnArray['RAWRESPONSE']=$plan->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Deletes a plan by ID.
-     *
-     * @param string $planId
-     * @return Array|Object
-     */
-    public function DeletePlan($planId){
-        try {
-             $createdPlan = new Plan();
-             $createdPlan->setId($planId);
-             $result = $createdPlan->delete($this->_api_context);
-             $returnArray['RESULT'] = 'Success';
-             $returnArray['DELETE_PLAN'] = $result->toArray();
-             $returnArray['RAWREQUEST']='{id:'.$planId.'}';
-             $returnArray['RAWRESPONSE']=$result->toJSON();
-             return $returnArray;             
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * @param Array $requestData
-     * @param string $type
-     * @return Array
-     */
-    public function CreateBillingAgreement($requestData)
-    {
-        $agreement = new Agreement();
-        if(isset($requestData['agreement'])){
-            $this->setArrayToMethods($this->checkEmptyObject($requestData['agreement']), $agreement);
-        }
-
-        // Add Plan ID
-        // Please note that the plan Id should be only set in this case.
-        $plan = new Plan();
-        $plan->setId($requestData['planId']);
-        $agreement->setPlan($plan);
-
-        // Add Payer
-        $payer = new Payer();
-        if(isset($requestData['payer'])){
-            $this->setArrayToMethods($this->checkEmptyObject($requestData['payer']), $payer);
-            if(isset($requestData['payerInfo'])){
-                $payerInfo = new PayerInfo();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['payerInfo']), $payerInfo);
-                $payer->setPayerInfo($payerInfo);
-            }
-            $agreement->setPayer($payer);
-        }
-
-        if($requestData['payer']['PaymentMethod'] == 'credit_card'){
-            // Add Credit Card to Funding Instruments
-            if(isset($requestData['creditCard'])){
-                $card = new CreditCard();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['creditCard']), $card);
-                $fundingInstrument = new FundingInstrument();
-                $fundingInstrument->setCreditCard($card);
-                $payer->setFundingInstruments(array($fundingInstrument));
-            }
-        }
-
-        // Add Shipping Address
-        if(isset($requestData['shippingAddress'])){
-            $shippingAddress = new ShippingAddress();
-            $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingAddress']), $shippingAddress);
-            $agreement->setShippingAddress($shippingAddress);
-        }
-
-        // ### Create Agreement
-        try {
-            // Please note that as the agreement has not yet activated, we wont be receiving the ID just yet.
-            $requestArray= clone $agreement;
-            $agreement = $agreement->create($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            if($requestData['payer']['PaymentMethod']=='paypal'){
-                $returnArray['ApprovalURL'] = $agreement->getApprovalLink();
-            }
-            $returnArray['AGREEMENT'] = $agreement->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for a billing agreement, by ID.
-     *
-     * @param string $agreementId
-     * @return Array|Object
-     */
-    public function GetBillingAgreement($agreementId){
-        try {
-            $agreement = Agreement::get($agreementId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';        
-            $returnArray['AGREEMENT']= $agreement->toArray();            
-            $returnArray['RAWREQUEST']='{id:'.$agreementId.'}';
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Bills the balance for an agreement, by ID
-     *
-     * @param string $agreementId
-     * @param string $note
-     * @return Array|Object
-     */
-    public function BillAgreementBalance($agreementId,$note){
-        try {            
-            $agreementStateDescriptor = new AgreementStateDescriptor();
-            $note = trim($note);
-            if(!empty($note)){
-                $agreementStateDescriptor->setNote($note);
-            }
-            $agreement = new Agreement();
-            $agreement->setId($agreementId);
-            $output = $agreement->billBalance($agreementStateDescriptor, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';  
-            $returnArray['BILL_AGREEMENT_BALANCE']= $output;
-            $returnArray['RAWREQUEST']='{id:'.$agreementId.'}';
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Sets the balance for an agreement, by ID.
-     *
-     * @param string $agreementId
-     * @param Array $amountArray
-     * @return Array|Object
-     */
-    public function SetAgreementBalance($agreementId,$amountArray){
-        try {            
-            
-            $Currency = new Currency();
-            $Currency->setCurrency($amountArray['Currency']);
-            $Currency->setValue($amountArray['value']);            
-            
-            $agreement = new Agreement();
-            $agreement->setId($agreementId);
-            
-            $output = $agreement->setBalance($Currency,$this->_api_context);
-            
-            $returnArray['RESULT'] = 'Success';  
-            $returnArray['AGREEMENT_BALANCE']= $output;
-            $returnArray['RAWREQUEST']='{id:'.$agreementId.'}';
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Suspends a billing agreement, by ID.
-     *
-     * @param string $agreementId
-     * @param string $note
-     * @return Array|Object
-     */
-    public function SuspendBillingAgreement($agreementId,$note){
-        try {
-            //Create an Agreement State Descriptor, explaining the reason to suspend.
-            $agreementStateDescriptor = new AgreementStateDescriptor();
-            $note = trim($note);
-            if(!empty($note)){
-                $agreementStateDescriptor->setNote($note);
-            }
-            $createdAgreement = new Agreement();
-            $createdAgreement->setId($agreementId);
-            $createdAgreement->suspend($agreementStateDescriptor, $this->_api_context);            
-            $agreement = Agreement::get($agreementId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';    
-            $returnArray['AGREEMENT']= $agreement->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$agreementId.'}';
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Reactivates a suspended billing agreement, by ID.
-     *
-     * @param string $agreementId
-     * @param string $note
-     * @return Array|Object
-     */
-    public function ReactivateBillingAgreement($agreementId,$note){
-        try {
-            
-            $agreementStateDescriptor = new AgreementStateDescriptor();
-            $note = trim($note);
-            if(!empty($note)){
-                $agreementStateDescriptor->setNote($note);
-            }
-            $suspendedAgreement = new Agreement();
-            $suspendedAgreement->setId($agreementId);
-            $suspendedAgreement->reActivate($agreementStateDescriptor, $this->_api_context);            
-            $agreement = Agreement::get($agreementId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';         
-            $returnArray['AGREEMENT']= $agreement->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$agreementId.'}';
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;             
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-
-    /**
-     * List transactions for a billing agreement by passing the ID of the agreement, as well as the start and end dates of the range of transactions to list, to the request URI.
-     *
-     * @param [type] $agreementId
-     * @param [type] $params  Parameters for search string.
-     * @return Array|Object
-     */
-    public function SearchBillingTransactions($agreementId,$params){
-        try {
-            $result = Agreement::searchTransactions($agreementId, $params, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';            
-            $returnArray['BILLING_TRANSACTIONS'] = $result->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$agreementId.'}';
-            $returnArray['RAWRESPONSE']=$result->toJSON();
-            return $returnArray;             
-        }  catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }                
-    }
-    
-    /**
-     * Updates details of a billing agreement, by ID.
-     *
-     * @param string $agreementId
-     * @param Array $agreement
-     * @return void
-     */
-    public function UpdateBillingAgreement($agreementId,$agreement){
-
-        if(count(array_filter($agreement['shipping_address'])) == 0){
-            unset($agreement['shipping_address']);
-        }
-        
-        try {            
-            $patch = new Patch();
-            $patch->setOp('replace')
-                ->setPath('/')
-                ->setValue(json_decode(json_encode(array_filter($agreement))));        
-
-            $patchRequest = new PatchRequest();
-            $patchRequest->addPatch($patch);
-
-            $createdAgreement = new Agreement();
-            $createdAgreement->setId($agreementId);
-            $requestArray= clone $createdAgreement;
-            $createdAgreement->update($patchRequest, $this->_api_context);            
-            $agreement = Agreement::get($agreementId, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AGREEMENT']= $agreement->toArray();            
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;            
-            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Cancels a billing agreement, by ID.
-     *
-     * @param string $agreementId
-     * @param string $note
-     * @return boolean
-     */
-    public function CancelBillingAgreement($agreementId,$note){
-        try {
-            
-            $agreementStateDescriptor = new AgreementStateDescriptor();
-            $note = trim($note);
-            if(!empty($note)){
-                $agreementStateDescriptor->setNote($note);
-            }
-            $cancelAgreement = new Agreement();
-            $cancelAgreement->setId($agreementId);
-            $requestArray = clone $cancelAgreement;
-            $cancelAgreement->cancel($agreementStateDescriptor, $this->_api_context);
-            $agreement = Agreement::get($agreementId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';            
-            $returnArray['AGREEMENT']=$agreement->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-
-    /**
-     *  Execute a billing agreement after buyer approval by passing the payment token to the request URI.
-     * @param $token
-     * @return Array
-     */
-    public function ExecuteAgreement($token){
-        $execute_agreement = new Agreement();
-        try {
-            // ## Execute Agreement
-            // Execute the agreement by passing in the token
-            $execute_agreement->execute($token, $this->_api_context);
-            $requestArray = clone $execute_agreement;
-            $agreement = Agreement::get($execute_agreement->getId(), $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AGREEMENT']=$agreement->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$agreement->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-}
diff --git a/src/angelleye/PayPal/rest/checkout_orders/CheckoutOrdersAPI.php b/src/angelleye/PayPal/rest/checkout_orders/CheckoutOrdersAPI.php
deleted file mode 100644
index a03b7fc3..00000000
--- a/src/angelleye/PayPal/rest/checkout_orders/CheckoutOrdersAPI.php
+++ /dev/null
@@ -1,328 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use \angelleye\PayPal\CheckoutOrdersClass;
-use \angelleye\PayPal\RestClass;
-
-/**
- * CheckoutOrdersAPI.
- * This class is responsible for Checkout Orders V2 API & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class CheckoutOrdersAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     * Creates an order.
-     * @param array $parameters
-     * @return array
-     */
-    public function CreateOrder($parameters) {
-
-        $requestBody = array(
-            'intent' => isset($parameters['intent']) ? $parameters['intent'] : '',
-            'application_context' => isset($parameters['application_context']) ? $parameters['application_context'] : '',
-            'purchase_units' => array(
-              isset($parameters['purchase_units']) ? $parameters['purchase_units'] : '',
-            ),
-            'payer' => (isset($parameters['payer']) && !empty($parameters['payer'])) ? $parameters['payer'] : ''
-        );
-        try {
-
-            $orderObject = new CheckoutOrdersClass();
-            $params = array_filter($requestBody);
-            $requestArray = json_encode($params);
-            $order = $orderObject->create_order($params,$this->_api_context);
-            $approval_link = $order->getApprovalLink();
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['APPROVAL_LINK'] = $approval_link;
-            $returnArray['ORDER'] = $order->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Captures a payment for an order.
-     * @param string $order_id
-     * @return array
-     */
-    public function CaptureOrder($order_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->capture($order_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['TRANSACTION_ID'] = $order->getCaptureId();
-            $returnArray['ORDER']=$order->toArray();
-            $returnArray['RAWREQUEST']='{order_id:'.$order_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Authorizes an order, by ID.
-     * @param string $order_id
-     * @return array
-     */
-    public function AuthorizeOrder($order_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->authorize($order_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            //$returnArray['TRANSACTION_ID'] = $order->getCaptureId();
-            $returnArray['ORDER']=$order->toArray();
-            $returnArray['RAWREQUEST']='{order_id:'.$order_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for an order, by ID.
-     * @param string $order_id
-     * @return array
-     */
-    public function GetOrderDetails($order_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->get($order_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            if(isset($order->intent) && $order->intent=='CAPTURE'){
-                $returnArray['TRANSACTION_ID'] = $order->getCaptureId();
-            }
-            if(isset($order->intent) && $order->intent=='AUTHORIZE'){
-                $authData = $order->getAuthId();
-                $returnArray['TRANSACTION_ID'] = $authData['id'];
-                $returnArray['AUTH_STATUS'] = $authData['status'];
-            }
-            $returnArray['ORDER']=$order->toArray();
-            $returnArray['RAWREQUEST']='{order_id:'.$order_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for an authorization, by ID.
-     * @param string $authorization_id
-     * @return array
-     */
-    public function GetAuthorizePaymentDetails($authorization_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->get_authorization($authorization_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AUTHORIZATION']=$order->toArray();
-            $returnArray['RAWREQUEST']='{authorization_id:'.$authorization_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for a captured payment, by ID.
-     * @param string $capture_id
-     * @return array
-     */
-    public function GetCapturedPaymentDetails($capture_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->get_capture($capture_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CAPTURE']=$order->toArray();
-            $returnArray['RAWREQUEST']='{capture_id:'.$capture_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Captures and processes an authorization, by ID.
-     * @param string $authorization_id
-     * @param array $requestBody
-     * @return array
-     */
-    public function CaptureAuthorizedPayment($authorization_id,$requestBody){
-        $orderObject = new CheckoutOrdersClass();
-        $params = array_filter($requestBody);
-        $requestArray = json_encode($params);
-        try {
-            $order = $orderObject->capture_authorization($authorization_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AUTHORIZATION']=$order->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Reauthorizes an authorized PayPal account payment, by ID.
-     * @param string $authorization_id
-     * @param array $requestBody
-     * @return array
-     */
-    public function Reauthorize($authorization_id,$requestBody){
-        $orderObject = new CheckoutOrdersClass();
-        $params = array_filter($requestBody);
-        $requestArray = json_encode($params);
-        try {
-            $order = $orderObject->reauthorize($authorization_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AUTHORIZATION']=$order->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Voids, or cancels, an authorization, by ID. You cannot void a fully captured authorization.
-     * @param string $authorization_id
-     * @return \angelleye\PayPal\Array|\angelleye\PayPal\Ojbect
-     */
-    public function VoidAuthorizedPayment($authorization_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->void($authorization_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AUTHORIZATION']=$order->toArray();
-            $returnArray['RAWREQUEST']='{authorization_id:'.$authorization_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Refunds a captured payment, by ID.
-     * @param $capture_id
-     * @param $requestBody
-     * @return \angelleye\PayPal\Array|\angelleye\PayPal\Ojbect
-     */
-    public function RefundCapturedPayment($capture_id,$requestBody){
-        $orderObject = new CheckoutOrdersClass();
-        $params = array_filter($requestBody);
-        $requestArray = json_encode($params);
-        try {
-            $order = $orderObject->refund($capture_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CAPTURE']=$order->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for a refund, by ID.
-     * @param string $refund_id
-     * @return \angelleye\PayPal\Array|\angelleye\PayPal\Ojbect
-     */
-    public function ShowRefundDetails($refund_id){
-        $orderObject = new CheckoutOrdersClass();
-        try {
-            $order = $orderObject->get_refund_details($refund_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REFUND']= $order->toArray();
-            $returnArray['RAWREQUEST']='{refund_id:'.$refund_id.'}';
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Updates an order by ID.
-     * @param string $order_id
-     * @param array $requestBody
-     * @return \angelleye\PayPal\Array|\angelleye\PayPal\Ojbect
-     */
-    public function UpdateOrder($order_id,$requestBody){
-        $orderObject = new CheckoutOrdersClass();
-        $params = array_filter($requestBody);
-        $requestArray = json_encode($params);
-        try {
-            $order = $orderObject->update_order($order_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REFUND']= $order->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$order->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-}
diff --git a/src/angelleye/PayPal/rest/customerdisputes/CustomerDisputesAPI.php b/src/angelleye/PayPal/rest/customerdisputes/CustomerDisputesAPI.php
deleted file mode 100644
index 21953479..00000000
--- a/src/angelleye/PayPal/rest/customerdisputes/CustomerDisputesAPI.php
+++ /dev/null
@@ -1,302 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use PayPal\Api\Plan;
-use \angelleye\PayPal\CustomerDisputesClass;
-use \angelleye\PayPal\RestClass;
-
-/**
- * CustomerDisputesAPI.
- * This class is responsible for Customer Disputes & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class CustomerDisputesAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     * Lists disputes with a full or summary set of details. Default is a summary set of details, which shows the dispute_id, reason, status, dispute_amount, create_time, and update_time fields.
-     *
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function ListDisputes($parameters) {
-        try {            
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $disputes = CustomerDisputesClass::list_disputes($params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTES'] = $disputes->toArray();            
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$disputes->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Shows details for a dispute, by ID.
-     *
-     * @param string $dispute_id
-     * @return Array|Object
-     */
-    public function ShowDisputeDetails($dispute_id){
-        $disputeObject = new CustomerDisputesClass();
-        try {
-            $dispute = $disputeObject->get($dispute_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']='{dispute_id:'.$dispute_id.'}';
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Accepts liability for a claim, by ID.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function AcceptClaim($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {
-            $params = $this->checkEmptyObject($parameters);            
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->dispute_accept_claim($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Settles a dispute in either the customer's or merchant's favor. 
-     * Merchants can make this call in the sandbox to complete end-to-end dispute resolution testing, 
-     * which mimics the dispute resolution that PayPal agents normally complete. 
-     * To make this call, the dispute status must be UNDER_REVIEW.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function SettleDispute($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {
-            $params = $this->checkEmptyObject($parameters);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->adjudicate($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Appeals a dispute, by ID.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function DisputesAppeal($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {
-            $params = array_map('array_filter', $parameters);
-            $params = array_filter($params);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->appeal($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }  
-    }
-    
-    /**
-     * Escalates the dispute, by ID, to a PayPal claim. To make this call, the stage in the dispute lifecycle must be INQUIRY.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function DisputesEscalate($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {            
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->escalate($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Makes an offer to the other party to resolve a dispute, by ID.
-     * To make this call, the stage in the dispute lifecycle must be INQUIRY.
-     * If the customer accepts the offer, PayPal automatically makes a refund.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function DisputesMakeOffer($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {            
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->make_offer($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Provides evidence for a dispute, by ID.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function ProvideEvidence($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {            
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->provide_evidence($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Updates the status of a dispute, by ID, from UNDER_REVIEW to either:
-     * 1) WAITING_FOR_BUYER_RESPONSE
-     * 2) WAITING_FOR_SELLER_RESPONSE
-     * 
-     * If action is BUYER_EVIDENCE The state updates to WAITING_FOR_BUYER_RESPONSE.
-     * If action is SELLER_EVIDENCE The state updates to WAITING_FOR_SELLER_RESPONSE.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function UpdateDisputeStatus($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {            
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->require_evidence($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Sends a message to the other party in the dispute, by ID.
-     *
-     * @param string $dispute_id
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function SendMessageToOtherParty($dispute_id,$parameters){
-        $disputeObject = new CustomerDisputesClass();
-        try {            
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $dispute = $disputeObject->send_message($dispute_id,$params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DISPUTE']=$dispute->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$dispute->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-}
diff --git a/src/angelleye/PayPal/rest/identity/IdentityAPI.php b/src/angelleye/PayPal/rest/identity/IdentityAPI.php
deleted file mode 100644
index 79a11859..00000000
--- a/src/angelleye/PayPal/rest/identity/IdentityAPI.php
+++ /dev/null
@@ -1,133 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use PayPal\Api\OpenIdSession;
-use PayPal\Api\OpenIdTokeninfo;;
-use PayPal\Api\OpenIdUserinfo;
-use PayPal\Exception\PayPalConnectionException;
-
-
-/**
- * IdentityAPI.
- * This class is responsible for Identity APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-
-class IdentityAPI {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */    
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray)
-    {   // setup PayPal api context 
-        $this->_api_context = new \PayPal\Rest\ApiContext(
-                new \PayPal\Auth\OAuthTokenCredential($configArray['ClientID'],$configArray['ClientSecret'])
-            );
-    }
-    
-    /**
-     * Obtain User Consent URL.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function GetUserConsentURL($requestData){
-        //Get Authorization URL returns the redirect URL that could be used to get user's consent
-        $redirectUrl = OpenIdSession::getAuthorizationUrl(
-            $requestData['redirectUri'],$requestData['scope'],
-            null,
-            null,
-            null,
-            $this->_api_context
-        );
-        $returnArray['RESULT'] = 'SUCCESS';
-        $returnArray['AUTH_URL'] = $redirectUrl;
-        $returnArray['RAWREQUEST'] = json_encode(array_filter($requestData));
-        return $returnArray;
-    }
-     
-    /**
-     * Use this call to retrieve user profile attributes.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function GetUserInfo($requestData){
-        try {
-            $tokenInfo = new OpenIdTokeninfo();
-            $tokenInfo = $tokenInfo->createFromRefreshToken(array('refresh_token' => $requestData['refreshToken']), $this->_api_context);
-            $params = array('access_token' => $tokenInfo->getAccessToken());
-            $userInfo = OpenIdUserinfo::getUserinfo($params, $this->_api_context);  
-            $returnArray['RESULT'] = 'SUCCESS';
-            $returnArray['USER_INFO'] = $userInfo->toArray();
-            $returnArray['RAWREQUEST'] = json_encode($params);
-            $returnArray['RAWRESPONSE'] = $userInfo->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $ex;   
-        }
-    }
-
-    /**
-     * Creates an Access Token from an Authorization Code.
-     * @param $code
-     * @return Array
-     */
-    public function GetUserConsentRedirect($code){
-        try {
-            // Obtain Authorization Code from Code, Client ID and Client Secret
-            $accessToken = OpenIdTokeninfo::createFromAuthorizationCode(array('code' => $code), null, null, $this->_api_context);
-            $returnArray['RESULT'] = 'SUCCESS';
-            $returnArray['AccessToken'] = $accessToken->toArray();
-            return $returnArray;
-        } catch (PayPalConnectionException $ex) {
-            echo "
";
-            print_r($ex);
-            exit;
-        }
-    }
-}
-?>
\ No newline at end of file
diff --git a/src/angelleye/PayPal/rest/invoice/InvoiceAPI.php b/src/angelleye/PayPal/rest/invoice/InvoiceAPI.php
deleted file mode 100755
index 0072566f..00000000
--- a/src/angelleye/PayPal/rest/invoice/InvoiceAPI.php
+++ /dev/null
@@ -1,1281 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use PayPal\Api\Address;
-use PayPal\Api\Amount;
-use PayPal\Api\BillingInfo;
-use PayPal\Api\CancelNotification;
-use PayPal\Api\Cost;
-use PayPal\Api\Currency;
-use PayPal\Api\FileAttachment;
-use PayPal\Api\Invoice;
-use PayPal\Api\InvoiceAddress;
-use PayPal\Api\InvoiceItem;
-use PayPal\Api\MerchantInfo;
-use PayPal\Api\Notification;
-use PayPal\Api\PaymentTerm;
-use PayPal\Api\PaymentDetail;
-use PayPal\Api\Phone;
-use PayPal\Api\Participant;
-use PayPal\Api\RefundDetail;
-use PayPal\Api\Search;
-use PayPal\Api\ShippingInfo;
-use PayPal\Api\ShippingCost;
-use PayPal\Api\Tax;
-use PayPal\Api\Template;
-use PayPal\Api\Templates;
-use PayPal\Api\TemplateData;
-use PayPal\Api\TemplateSettings;
-use PayPal\Api\TemplateSettingsMetadata;
-use \angelleye\PayPal\RestClass;
-
-/**
- * InvoiceAPI.
- * This class is responsible for Invoice APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class InvoiceAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */ 
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-    
-    /**
-     *  Creates an invoice. Include invoice details including merchant information in the request.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function CreateInvoice($requestData,$third_party=false,$refesh_token=''){
-            try {
-                    $invoice = new Invoice();
-                    
-                    // ### Setting Merchant info to invoice object.
-                    // ### Start
-                    $MerchantInfo = new MerchantInfo();
-                    if( isset($requestData['merchantInfo'])){
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantInfo']), $MerchantInfo);
-                        if( isset($requestData['merchantPhone'])){
-                            $merchantPhone = new Phone();
-                            $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantPhone']), $merchantPhone);
-                            $MerchantInfo->setPhone($merchantPhone);
-                        }
-                        if(isset($requestData['merchantAddress'])){
-                            $merchantAddress = new Address();
-                            $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantAddress']), $merchantAddress);
-                            $MerchantInfo->setAddress($merchantAddress);
-                        }
-                        $invoice->setMerchantInfo($MerchantInfo);
-                    }
-                    // ### End
-                    
-                    // ### Setting cc_info
-                    // ### Start
-                    $Participant = new Participant();
-                    if(isset($requestData['ccInfo'])){
-                       $this->setArrayToMethods($this->checkEmptyObject($requestData['ccInfo']), $Participant);
-                        $participantArray = $this->checkEmptyObject((array)$Participant);
-                        if (!empty($participantArray)) {
-                            $invoice->setCcInfo(array($Participant));
-                        }
-                    }
-                    // ### End
-                    
-                    // ### Setting Minimum Amount Due
-                    // ### Start                            
-                    $MinAmountCurrency = new Currency();
-                    if(isset($requestData['MinimumAmountDue'])){
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['MinimumAmountDue']), $MinAmountCurrency);
-                    }
-                    $MinAmountCurrencyArray = $this->checkEmptyObject((array)$MinAmountCurrency);
-                    if (!empty($MinAmountCurrencyArray)) {
-                        $invoice->setMinimumAmountDue($MinAmountCurrency);
-                    }
-                    // ### End
-                    
-                    // ### Setting Billing Info to invoice object. 
-                    // ### Start
-                    $BillingInfo = new BillingInfo();
-                    if(isset($requestData['billingInfo'])){
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfo']), $BillingInfo);
-                    }
-                    if (isset($requestData['billingInfoAddress'])) {
-                        $InvoiceAddress = new InvoiceAddress();
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoAddress']), $InvoiceAddress);
-                        $BillingInfo->setAddress($InvoiceAddress);
-                    }
-                    if (isset($requestData['billingInfoPhone'])) {
-                        $billingPhone = new Phone();
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoPhone']), $billingPhone);
-                        $BillingInfo->setPhone($billingPhone);
-                    }
-
-                    $BillingInfoArray = $this->checkEmptyObject((array)$BillingInfo);
-                    if (!empty($BillingInfoArray)) {
-                        $invoice->setBillingInfo(array($BillingInfo));                        
-                    }
-                    //End
-                    
-                    // ### Add items in Invoice object.
-                    // ### Start.    
-                   if(isset($requestData['itemArray'])) {
-                       $itemArray = array();
-                       foreach ($requestData['itemArray'] as $item) {
-                           $InvoiceItem = new InvoiceItem();
-
-                           if (isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0) {
-                               $ItemCurrency = new Currency();
-                               $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                               $InvoiceItem->setUnitPrice($ItemCurrency);
-                           }
-                           unset($item['UnitPrice']);
-                           if (isset($item['Tax']) && count(array_filter($item['Tax'])) > 0) {
-                               $ItemTax = new Tax();
-                               $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                               $InvoiceItem->setTax($ItemTax);
-                           }
-                           unset($item['Tax']);
-                           if (isset($item['Discount']) && count(array_filter($item['Discount'])) > 0) {
-                               $ItemCost = new Cost();
-                               $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                               $InvoiceItem->setDiscount($ItemCost);
-                           }
-                           unset($item['Discount']);
-
-                           $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                           array_push($itemArray, $InvoiceItem);
-                       }
-                       $itemArrayData = $this->checkEmptyObject($itemArray);
-                       if (!empty($itemArrayData)) {
-                           $invoice->setItems($itemArray);
-                       }
-                   }
-                    // ### END
-                    
-                    // #### Final Discount
-                    // You can add final discount to the invoice as shown below. You could either use "percent" or "value" when providing the discount
-                    
-                    if(isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Percent'){
-                        $FinalDiscountCost = new Cost();
-                        $FinalDiscountCost->setPercent($requestData['finalDiscountForInvoice']['Percent']);                        
-                        $invoice->setDiscount($FinalDiscountCost);   
-                    }
-                    if(isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Amount'){
-                        $FinalDiscountCost = new Cost();
-                        $discountCurrency = new Currency();
-                        $discountCurrency->setCurrency($requestData['finalDiscountForInvoice']['Amount']['Currency']);
-                        $discountCurrency->setValue($requestData['finalDiscountForInvoice']['Amount']['Value']);
-                        $FinalDiscountCost->setAmount($discountCurrency);
-                        $invoice->setDiscount($FinalDiscountCost);
-                    }
-                    
-                    if(isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0){
-                        $PaymentTerm = new PaymentTerm();
-                        $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                        $invoice->setPaymentTerm($PaymentTerm);
-                    }
-                    
-                    // ### Shipping Information
-                    // ### Start
-                    $ShippingInfo = new ShippingInfo();
-                    if (isset($requestData['shippingInfo'])) {
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfo']), $ShippingInfo);
-                    }
-                    if (isset($requestData['shippingInfoPhone'])) {
-                        $ShippingInfoPhone = new Phone();
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                        $ShippingInfo->setPhone($ShippingInfoPhone);
-                    }                    
-                    if (isset($requestData['shippingInfoAddress'])) {
-                        $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                        $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-                    }
-
-                    $shippingInfoArray = $this->checkEmptyObject((array)$ShippingInfo);
-                    if (!empty($shippingInfoArray)) {
-                        $invoice->setShippingInfo($ShippingInfo);
-                    }
-                    if (isset($requestData['invoiceData'])) {
-                        $this->setArrayToMethods($this->checkEmptyObject($requestData['invoiceData']), $invoice);
-                    }
-                    
-                    if(isset($requestData['shippingCost']['type']) && $requestData['shippingCost']['type'] == 'Amount'){
-                        $shippingCurrency = new Currency();
-                        $shippingCurrency->setCurrency($requestData['shippingCost']['Amount']['Currency']);
-                        $shippingCurrency->setValue($requestData['shippingCost']['Amount']['Value']);
-                        $ShippingCost = new ShippingCost();
-                        $ShippingCost->setAmount($shippingCurrency);
-                        $invoice->setShippingCost($ShippingCost);       
-                    }
-
-                    
-                    if(isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0){
-                        foreach ($requestData['attachments'] as $value) {
-                            $attachment = new FileAttachment();
-                            $attachment->setName($value['Name']);
-                            $attachment->setUrl($value['url']);
-                            $invoice->setAttachments(array($attachment));
-                        }                        
-                    }
-                                                                                
-                // ### Create Invoice
-                // Create an invoice by calling the invoice->create() method
-                if($third_party === true  && !empty($refesh_token)){
-                    $invoice->updateAccessToken($refesh_token, $this->_api_context);
-                }
-                $requestArray = clone $invoice;
-                $invoice->create($this->_api_context);
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['INVOICE']=$invoice->toArray();                
-                $returnArray['RAWREQUEST']=$requestArray->toJSON();
-                $returnArray['RAWRESPONSE']=$invoice->toJSON();
-                return $returnArray;
-            } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-                return $this->createErrorResponse($ex);
-            }        
-    }        
-    
-    /**
-     * Lists some or all merchant invoices. Filters the response by any specified optional query string parameters.
-     *
-     * @param Array $params
-     * @return Array|Object
-     */
-    public function ListInvoice($params,$third_party=false,$refesh_token=''){
-        try {
-            $apiContext = $this->_api_context;
-            if($third_party === true  && !empty($refesh_token)){
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $invoices = Invoice::getAll($params, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICES'] = $invoices->toArray();
-            return $returnArray;
-            
-        }  catch (\PayPal\Exception\PayPalConnectionException $ex) {
-               return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Gets the details for a specified invoice, by ID.
-     *
-     * @param string $invoiceId
-     * @return Array|Object
-     */
-    public function GetInvoice($invoiceId){
-        try {
-            $invoice = Invoice::get($invoiceId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$invoiceId.'}';
-            $returnArray['RAWRESPONSE']=$invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Creates third party invoice on someone else's behalf.
-     * This requires using `Obtain User's Consent` to fetch the refresh token of the third party merchant.     
-     *  
-     * @param string $invoiceId
-     * @param string $refreshToken
-     * @return Array|Object
-     */
-    public function GetThirdPartyInvoice($invoiceId,$refreshToken){
-        try {          
-            $apiContext = $this->_api_context;
-            $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken);
-            $invoice = Invoice::get($invoiceId, $apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$invoiceId.'}';
-            $returnArray['RAWRESPONSE']=$invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Cancels an invoice, by ID.
-     *
-     * @param Array $cancelNotification
-     * @param string $InvoiceID
-     * @return boolean
-     */
-    public function CancelInvoice($cancelNotification,$InvoiceID,$third_party=false,$refesh_token=''){
-        try {
-            $notify = new CancelNotification();
-            $this->setArrayToMethods(array_filter($cancelNotification), $notify);
-            
-            $invoice = new Invoice();
-            $invoice->setId($InvoiceID);
-            if($third_party === true  && !empty($refesh_token)){
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $requestArray = clone $invoice;
-            $cancelStatus = $invoice->cancel($notify, $this->_api_context);
-                        
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CANCEL_STATUS'] = $cancelStatus;
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$cancelStatus;
-            return $returnArray;                   
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Marks the status of a specified invoice, by ID, as refunded.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function RecordRefund($requestData,$third_party=false,$refesh_token=''){
-        try {
-            $invoice  = new Invoice();
-            $invoice->setId($requestData['invoiceId']);
-            if($third_party === true  && !empty($refesh_token)){
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $refund = new RefundDetail();
-            if(isset($requestData['refundDetail'])){
-                $this->setArrayToMethods($requestData['refundDetail'], $refund);
-            }
-            
-            if(isset($requestData['amount']) && count(array_filter($requestData['amount'])) > 0){
-                $amt= new Currency(json_encode($requestData['amount']));
-                $refund->setAmount($amt);
-            }
-            $requestArray = clone $invoice;
-            $refundStatus = $invoice->recordRefund($refund, $this->_api_context);
-            $invoice = Invoice::get($requestData['invoiceId'], $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REFUND_STATUS'] = $refundStatus;
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$invoice->toJSON();
-            return $returnArray;                                                
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Sends a reminder to the payer about an invoice, by ID.
-     *
-     * @param Array $remindNotification
-     * @param string $InvoiceID
-     * @return Array|Object
-     */
-    public function RemindInvoice($remindNotification,$InvoiceID,$third_party=false,$refesh_token=''){
-        try {
-            $apiContext = $this->_api_context;
-            if($third_party === true  && !empty($refesh_token)){
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $invoice  = new Invoice();
-            $invoice->setId($InvoiceID);
-            $notify = new Notification();
-            $this->setArrayToMethods(array_filter($remindNotification), $notify);
-            $remindStatus = $invoice->remind($notify, $apiContext);
-            $requestArray = clone $invoice;
-            $invoice = Invoice::get($InvoiceID, $apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REMIND_STATUS'] = $remindStatus;
-            $returnArray['REMIND_INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Generate a QR code for an invoice by passing the invoice ID.
-     *
-     * @param Array $parameters
-     * @param string $InvoiceID
-     * @param string $path
-     * @return Array|Object
-     */
-    public function RetrieveQRCode($parameters,$InvoiceID,$path,$third_party=false,$refesh_token=''){
-        
-        try{
-            $apiContext = $this->_api_context;
-            if($third_party === true  && !empty($refesh_token)){
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $image = Invoice::qrCode($InvoiceID, array_filter($parameters), $apiContext);
-            $path = $image->saveToFile($path);
-            $returnArray['RESULT'] = 'Success';            
-            return array('Image' => $image->getImage());
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }                
-    }
-    
-    /**
-     * Searches for an invoice or invoices. Include a search object that specifies your search criteria in the request.
-     *
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function SearchInvoices($parameters,$third_party=false,$refesh_token=''){
-        
-        try{
-            $apiContext = $this->_api_context;
-            if($third_party === true  && !empty($refesh_token)){
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $search = new Search(json_encode(array_filter($parameters)));            
-            $invoices = Invoice::search($search, $apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICES'] = $invoices->toArray();
-            $returnArray['RAWREQUEST']=json_encode(array_filter($parameters));
-            $returnArray['RAWRESPONSE']=$invoices->toJSON();
-            return $returnArray;
-            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Fully updates an invoice, by ID.
-     *
-     * @param Array|Object $requestData
-     * @return Array|Object
-     */
-    public function UpdateInvoice($requestData,$third_party=false,$refesh_token=''){
-        
-        try {       
-            $invoice = new Invoice();
-            $invoice->setId($requestData['InvoiceID']);
-            // ### Setting Merchant info to invoice object.
-            // ### Start
-            $MerchantInfo = new MerchantInfo();
-            if( isset($requestData['merchantInfo'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantInfo']), $MerchantInfo);
-                if( isset($requestData['merchantPhone'])){
-                    $merchantPhone = new Phone();
-                    $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                if(isset($requestData['merchantAddress'])){
-                    $merchantAddress = new Address();
-                    $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoice->setMerchantInfo($MerchantInfo);
-            }
-            // ### End
-
-            // ### Setting cc_info
-            // ### Start
-            $Participant = new Participant();
-            if(isset($requestData['ccInfo'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['ccInfo']), $Participant);
-                $participantArray = $this->checkEmptyObject((array)$Participant);
-                if (!empty($participantArray)) {
-                    $invoice->setCcInfo(array($Participant));
-                }
-            }
-            // ### End
-
-            // ### Setting Minimum Amount Due
-            // ### Start
-            $MinAmountCurrency = new Currency();
-            if(isset($requestData['MinimumAmountDue'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['MinimumAmountDue']), $MinAmountCurrency);
-            }
-            $MinAmountCurrencyArray = $this->checkEmptyObject((array)$MinAmountCurrency);
-            if (!empty($MinAmountCurrencyArray)) {
-                $invoice->setMinimumAmountDue($MinAmountCurrency);
-            }
-            // ### End
-
-            // ### Setting Billing Info to invoice object.
-            // ### Start
-            $BillingInfo = new BillingInfo();
-            if(isset($requestData['billingInfo'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfo']), $BillingInfo);
-            }
-            if (isset($requestData['billingInfoAddress'])) {
-                $InvoiceAddress = new InvoiceAddress();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoAddress']), $InvoiceAddress);
-                $BillingInfo->setAddress($InvoiceAddress);
-            }
-            if (isset($requestData['billingInfoPhone'])) {
-                $billingPhone = new Phone();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoPhone']), $billingPhone);
-                $BillingInfo->setPhone($billingPhone);
-            }
-
-            $BillingInfoArray = $this->checkEmptyObject((array)$BillingInfo);
-            if (!empty($BillingInfoArray)) {
-                $invoice->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-            // ### Add items in Invoice object.
-            // ### Start.
-            if(isset($requestData['itemArray'])) {
-
-                $itemArray = array();
-                foreach ($requestData['itemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if (isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0) {
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->setUnitPrice($ItemCurrency);
-                    }
-                    unset($item['UnitPrice']);
-                    if (isset($item['Tax']) && count(array_filter($item['Tax'])) > 0) {
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-                    if (isset($item['Discount']) && count(array_filter($item['Discount'])) > 0) {
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                    array_push($itemArray, $InvoiceItem);
-                }
-                $itemArrayData = $this->checkEmptyObject($itemArray);
-                if (!empty($itemArrayData)) {
-                    $invoice->setItems($itemArray);
-                }
-            }
-            // ### END
-
-            // #### Final Discount
-            // You can add final discount to the invoice as shown below. You could either use "percent" or "value" when providing the discount
-
-            if(isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Percent'){
-                $FinalDiscountCost = new Cost();
-                $FinalDiscountCost->setPercent($requestData['finalDiscountForInvoice']['Percent']);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-            if(isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Amount'){
-                $FinalDiscountCost = new Cost();
-                $discountCurrency = new Currency();
-                $discountCurrency->setCurrency($requestData['finalDiscountForInvoice']['Amount']['Currency']);
-                $discountCurrency->setValue($requestData['finalDiscountForInvoice']['Amount']['Value']);
-                $FinalDiscountCost->setAmount($discountCurrency);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-            if(isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Amount'){
-                $FinalDiscountCost = new Cost();
-                $discountCurrency = new Currency();
-                $discountCurrency->setCurrency($requestData['finalDiscountForInvoice']['Amount']['Currency']);
-                $discountCurrency->setValue($requestData['finalDiscountForInvoice']['Amount']['Value']);
-                $FinalDiscountCost->setAmount($discountCurrency);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-
-            if(isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0){
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoice->setPaymentTerm($PaymentTerm);
-            }
-
-            // ### Shipping Information
-            // ### Start
-            $ShippingInfo = new ShippingInfo();
-            if (isset($requestData['shippingInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfo']), $ShippingInfo);
-            }
-            if (isset($requestData['shippingInfoPhone'])) {
-                $ShippingInfoPhone = new Phone();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                $ShippingInfo->setPhone($ShippingInfoPhone);
-            }
-            if (isset($requestData['shippingInfoAddress'])) {
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-            }
-
-            $shippingInfoArray = $this->checkEmptyObject((array)$ShippingInfo);
-            if (!empty($shippingInfoArray)) {
-                $invoice->setShippingInfo($ShippingInfo);
-            }
-            if (isset($requestData['invoiceData'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['invoiceData']), $invoice);
-            }
-
-            if(isset($requestData['shippingCost']['type']) && $requestData['shippingCost']['type'] == 'Amount'){
-                $shippingCurrency = new Currency();
-                $this->setArrayToMethods(array_filter($requestData['shippingCost']['Currency']), $shippingCurrency);
-                $ShippingCost = new ShippingCost();
-                $ShippingCost->setAmount($shippingCurrency);
-                $invoice->setShippingCost($ShippingCost);
-            }
-            if(isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0){
-                foreach ($requestData['attachments'] as $key => $value) {
-                    $attachment = new FileAttachment();
-                    $attachment->setName($value['Name']);
-                    $attachment->setUrl($value['Url']);
-                    $invoice->setAttachments(array($attachment));
-                }
-            }
-            if(isset($requestData['shippingCost']['type']) && $requestData['shippingCost']['type'] == 'Amount'){
-                $shippingCurrency = new Currency();
-                $shippingCurrency->setCurrency($requestData['shippingCost']['Amount']['Currency']);
-                $shippingCurrency->setValue($requestData['shippingCost']['Amount']['Value']);
-                $ShippingCost = new ShippingCost();
-                $ShippingCost->setAmount($shippingCurrency);
-                $invoice->setShippingCost($ShippingCost);
-            }
-            $this->setArrayToMethods(array_filter($requestData['invoiceData']), $invoice);            
-
-            if($third_party === true  && !empty($refesh_token)){
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $requestArray = clone $invoice;
-            $invoice->update($this->_api_context);
-            $invoice = Invoice::get($invoice->getId(), $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$invoice->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-          return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Sends an invoice, by ID, to a customer. 
-     *
-     * @param string $invoiceId
-     * @param boolean $third_party
-     * @param  string $refresh_token
-     * @return Array|Object
-     */
-    public function SendInvoice($invoiceId,$third_party=false,$refresh_token=''){
-        try {
-            $invoice = new Invoice();
-            $invoice->setId($invoiceId);
-            if($third_party === true  && !empty($refresh_token)){
-                $invoice->updateAccessToken($refresh_token, $this->_api_context);
-            }
-            $sendStatus = $invoice->send($this->_api_context);
-            $Getinvoice = Invoice::get($invoice->getId(), $this->_api_context);
-
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['SEND_STATUS'] = $sendStatus;
-            $returnArray['INVOICE'] = $Getinvoice->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$invoiceId.'}';
-            $returnArray['RAWRESPONSE']=$Getinvoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Deletes invoices in the DRAFT or SCHEDULED state, by ID. 
-     *
-     * @param string $invoiceId
-     * @return Array|Object
-     */
-    public function DeleteInvoice($invoiceId,$third_party=false,$refesh_token=''){
-        
-        try{
-            $invoice = new Invoice();
-            $invoice->setId($invoiceId);
-            if($third_party === true  && !empty($refesh_token)){
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $deleteStatus = $invoice->delete($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DELETE_STATUS'] = $deleteStatus;
-            $returnArray['RAWREQUEST']='{id:'.$invoiceId.'}';
-            $returnArray['RAWRESPONSE']=$deleteStatus;
-            return $returnArray;            
-        }
-        catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Generates the next invoice number that is available to the merchant.
-     * The next invoice number uses the prefix and suffix from the last invoice number and increments the number by one.
-     *
-     * @return Array|Object
-     */
-    public function GetNextInvoiceNumber($third_party=false,$refesh_token=''){
-        try {
-            $apiContext = $this->_api_context;
-            if($third_party === true  && !empty($refesh_token)){
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $number = Invoice::generateNumber($apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE_NUMBER'] = $number->toArray();
-            $returnArray['RAWREQUEST']='';
-            $returnArray['RAWRESPONSE']=$number->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     *Marks the status of a specified invoice, by ID, as paid.
-     *
-     * @param string $invoiceId
-     * @param Array $record
-     * @param Array $amount
-     * @return Array|Object
-     */
-    public function RecordPayment($invoiceId,$record,$amount,$third_party=false,$refesh_token=''){
-        try{
-            $invoice = new Invoice();
-            $invoice->setId($invoiceId);
-            if($third_party === true  && !empty($refesh_token)){
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $PaymentDetail = new PaymentDetail();
-            $this->setArrayToMethods(array_filter($record), $PaymentDetail);
-            
-            if(count(array_filter($amount)) > 0){
-                $amt= new Currency(json_encode($amount));
-                $PaymentDetail->setAmount($amt);
-            }
-            
-            $recordStatus = $invoice->recordPayment($PaymentDetail, $this->_api_context);
-            
-            $returnInvoice = Invoice::get($invoiceId, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['RECORD_STATUS'] = $recordStatus;
-            $returnArray['INVOICE'] = $returnInvoice->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$invoiceId.'}';
-            $returnArray['RAWRESPONSE']=$returnInvoice->toJSON();
-            return $returnArray;
-        }
-        catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Creates an invoice template.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function CreateInvoiceTemplate($requestData){
-        
-        try {
-            $invoiceTemplateData = new TemplateData();
-
-            /**
-             * Setting Items in Invoice Template
-             */
-            if(isset($requestData['InvoiceItemArray'])){
-                $itemArray = array();
-
-                foreach ($requestData['InvoiceItemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if(isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0){
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->setUnitPrice($ItemCurrency);
-                    }
-                    unset($item['UnitPrice']);
-
-                    if(isset($item['Tax']) && count(array_filter($item['Tax'])) > 0){
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-
-                    if(isset($item['Discount']) && count(array_filter($item['Discount'])) > 0){
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    if(count(array_filter($item))>0){
-                        $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                        array_push($itemArray, $InvoiceItem);
-                        $invoiceTemplateData->addItem($InvoiceItem);
-                    }
-                }
-            }
-
-
-            // ### Setting Merchant info to invoice template object.
-            // ### Start
-            if(isset($requestData['merchantInfo'])){
-                $MerchantInfo = new MerchantInfo();
-                if( isset($requestData['merchantInfo']) && count(array_filter($requestData['merchantInfo'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['merchantInfo']), $MerchantInfo);
-                }
-                $merchantPhone = new Phone();
-                if( isset($requestData['merchantPhone']) && count(array_filter($requestData['merchantPhone'])) > 0 ){
-                    $this->setArrayToMethods(array_filter($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                $merchantAddress = new Address();
-                if(isset($requestData['merchantAddress']) && count(array_filter($requestData['merchantAddress'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoiceTemplateData->setMerchantInfo($MerchantInfo);
-            }
-
-            
-            
-            // ### End
-
-            // ### Setting Billing Info to invoice object. 
-            // ### Start
-
-            if(isset($requestData['billingInfo'])){
-                $BillingInfo = new BillingInfo();
-                if( isset($requestData['billingInfo']) && count(array_filter($requestData['billingInfo'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['billingInfo']), $BillingInfo);
-                }
-
-                $InvoiceAddress = new InvoiceAddress();
-                if(isset($requestData['billingInfoAddress']) && count(array_filter($requestData['billingInfoAddress'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoAddress']), $InvoiceAddress);
-                    $BillingInfo->setAddress($InvoiceAddress);
-                }
-
-                $billingPhone = new Phone();
-                if(count(array_filter($requestData['billingInfoPhone'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoPhone']), $billingPhone);
-                    $BillingInfo->setPhone($billingPhone);
-                }
-                $invoiceTemplateData->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-
-            // ### Shipping Information
-            // ### Start
-
-            if(isset($requestData['shippingInfo'])){
-                $ShippingInfo = new ShippingInfo();
-                $this->setArrayToMethods(array_filter($requestData['shippingInfo']), $ShippingInfo);
-
-                $ShippingInfoPhone = new Phone();
-                if(isset($requestData['shippingInfoPhone']) && count(array_filter($requestData['shippingInfoPhone'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                    $ShippingInfo->setPhone($ShippingInfoPhone);
-                }
-
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                if(isset($requestData['shippingInfoAddress']) && count(array_filter($requestData['shippingInfoAddress'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                    $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-                }
-                $invoiceTemplateData->setShippingInfo($ShippingInfo);
-            }
-            if(isset($requestData['templateData'])){
-                if(isset($requestData['templateData']['MinimumAmountDue']) && count(array_filter($requestData['templateData']['MinimumAmountDue'])) > 0){
-                    $TemplateMinimumAmountDueCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['MinimumAmountDue']), $TemplateMinimumAmountDueCurrency);
-                    $invoiceTemplateData->setMinimumAmountDue($TemplateMinimumAmountDueCurrency);
-                }
-                unset($requestData['templateData']['MinimumAmountDue']);
-
-                if(isset($requestData['templateData']['TotalAmount']) && count(array_filter($requestData['templateData']['TotalAmount'])) > 0){
-                    $TemplateTotalAmountCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['TotalAmount']), $TemplateTotalAmountCurrency);
-                    $invoiceTemplateData->setTotalAmount($TemplateTotalAmountCurrency);
-                }
-                unset($requestData['templateData']['TotalAmount']);
-                $this->setArrayToMethods(array_filter($requestData['templateData']), $invoiceTemplateData);
-            }
-
-            $templateDataCcInfo = isset($requestData['TemplateDataCcInfo']) ? trim($requestData['TemplateDataCcInfo']) : '';
-            if(!empty($templateDataCcInfo)){
-                $invoiceTemplateData->addCcInfo($templateDataCcInfo);
-            }
-
-            if(isset($requestData['templateDiscount']) && count(array_filter($requestData['templateDiscount'])) > 0){
-                $templateDiscountCost = new Cost();
-                $this->setArrayToMethods(array_filter($requestData['templateDiscount']), $templateDiscountCost);
-                $invoiceTemplateData->setDiscount($templateDiscountCost);
-            }
-
-            if(isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0){
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoiceTemplateData->setPaymentTerm($PaymentTerm);
-            }
-
-            if(isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0){
-                $attachment = new FileAttachment();
-                $this->setArrayToMethods(array_filter($requestData['attachments']), $attachment);
-                $invoiceTemplateData->setAttachments(array($attachment));
-            }
-
-             // ### Template Settings    
-            $displayPreferences = new TemplateSettingsMetadata();
-            if(isset($requestData['TemplateSettingsMetadata']) && count(array_filter($requestData['TemplateSettingsMetadata']))>0){
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettingsMetadata']), $displayPreferences);
-            }
-            
-            $settingDate = new TemplateSettings();
-            if(isset($requestData['TemplateSettings']) && count(array_filter($requestData['TemplateSettings']))>0){
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettings']), $settingDate);
-            }
-
-            if(count(array_filter((array)$displayPreferences)) > 0){
-                $settingDate->setDisplayPreference($displayPreferences);
-            }
-            
-            // ### Template
-            $invoiceTemplate = new Template();
-            if(isset($requestData['Template']) && count(array_filter($requestData['Template'])) > 0){
-                $this->setArrayToMethods(array_filter($requestData['Template']), $invoiceTemplate);
-            }
-            
-            if(count(array_filter((array)$invoiceTemplateData)) > 0){
-                $invoiceTemplate->setTemplateData($invoiceTemplateData);
-            }
-            
-            if(count(array_filter((array)$settingDate)) > 0){
-                $invoiceTemplate->addSetting($settingDate);
-            }
-            $requestArray = clone $invoiceTemplate;
-            $invoiceTemplate->create($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['TEMPLATE'] = $invoiceTemplate->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$invoiceTemplate->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Deletes a template, by ID.
-     *
-     * @param string $template_id
-     * @return Array|Object
-     */
-    public function DeleteInvoiceTemplate($template_id){
-        try {
-            $template = new Template();
-            $template->setTemplateId($template_id);
-            $deleteStatus = $template->delete($this->_api_context);                        
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DELETE_STATUS'] = $deleteStatus;
-            $returnArray['RAWREQUEST']='{id:'.$template_id.'}';
-            $returnArray['RAWRESPONSE']=$deleteStatus;
-            return $returnArray;                                                     
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Lists merchant-created templates with associated details
-     *
-     * @param Array $fields
-     * @return Array|Object
-     */
-    public function GetAllInvoiceTemplates($fields){
-        
-        try {
-            $templates = Templates::getAll($fields, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE_TEMPLATES'] = $templates->toArray();
-            $returnArray['RAWREQUEST']= json_encode($fields);
-            $returnArray['RAWRESPONSE']=$templates->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Shows details for a template, by ID.
-     *
-     * @param string $templateId
-     * @return Array|Object
-     */
-    public function GetInvoiceTemplate($templateId){
-        try {
-            $template = Template::get($templateId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['TEMPLATE'] = $template->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$templateId.'}';
-            $returnArray['RAWRESPONSE']=$template->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Updates a template, by ID.
-     *
-     * @param string  $templateId
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function UpdateInvoiceTemplate($templateId,$requestData){
-        try {
-            $invoiceTemplateData = new TemplateData();
-            /**
-             * Setting Items in Invoice Template
-             */
-            if(isset($requestData['InvoiceItemArray'])){
-                $itemArray = array();
-
-                foreach ($requestData['InvoiceItemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if(isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0){
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->setUnitPrice($ItemCurrency);
-                    }
-                    unset($item['UnitPrice']);
-
-                    if(isset($item['Tax']) && count(array_filter($item['Tax'])) > 0){
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-
-                    if(isset($item['Discount']) && count(array_filter($item['Discount'])) > 0){
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    if(count(array_filter($item))>0){
-                        $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                        array_push($itemArray, $InvoiceItem);
-                        $invoiceTemplateData->addItem($InvoiceItem);
-                    }
-                }
-            }
-
-
-            // ### Setting Merchant info to invoice template object.
-            // ### Start
-            if(isset($requestData['merchantInfo'])){
-                $MerchantInfo = new MerchantInfo();
-                if( isset($requestData['merchantInfo']) && count(array_filter($requestData['merchantInfo'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['merchantInfo']), $MerchantInfo);
-                }
-                $merchantPhone = new Phone();
-                if( isset($requestData['merchantPhone']) && count(array_filter($requestData['merchantPhone'])) > 0 ){
-                    $this->setArrayToMethods(array_filter($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                $merchantAddress = new Address();
-                if(isset($requestData['merchantAddress']) && count(array_filter($requestData['merchantAddress'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoiceTemplateData->setMerchantInfo($MerchantInfo);
-            }
-
-            // ### End
-
-            // ### Setting Billing Info to invoice object.
-            // ### Start
-
-            if(isset($requestData['billingInfo'])){
-                $BillingInfo = new BillingInfo();
-                if( isset($requestData['billingInfo']) && count(array_filter($requestData['billingInfo'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['billingInfo']), $BillingInfo);
-                }
-
-                $InvoiceAddress = new InvoiceAddress();
-                if(isset($requestData['billingInfoAddress']) && count(array_filter($requestData['billingInfoAddress'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoAddress']), $InvoiceAddress);
-                    $BillingInfo->setAddress($InvoiceAddress);
-                }
-
-                $billingPhone = new Phone();
-                if(count(array_filter($requestData['billingInfoPhone'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoPhone']), $billingPhone);
-                    $BillingInfo->setPhone($billingPhone);
-                }
-                $invoiceTemplateData->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-
-            // ### Shipping Information
-            // ### Start
-
-            if(isset($requestData['shippingInfo'])){
-                $ShippingInfo = new ShippingInfo();
-                $this->setArrayToMethods(array_filter($requestData['shippingInfo']), $ShippingInfo);
-
-                $ShippingInfoPhone = new Phone();
-                if(isset($requestData['shippingInfoPhone']) && count(array_filter($requestData['shippingInfoPhone'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                    $ShippingInfo->setPhone($ShippingInfoPhone);
-                }
-
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                if(isset($requestData['shippingInfoAddress']) && count(array_filter($requestData['shippingInfoAddress'])) > 0){
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                    $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-                }
-                $invoiceTemplateData->setShippingInfo($ShippingInfo);
-            }
-            if(isset($requestData['templateData'])){
-                if(isset($requestData['templateData']['MinimumAmountDue']) && count(array_filter($requestData['templateData']['MinimumAmountDue'])) > 0){
-                    $TemplateMinimumAmountDueCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['MinimumAmountDue']), $TemplateMinimumAmountDueCurrency);
-                    $invoiceTemplateData->setMinimumAmountDue($TemplateMinimumAmountDueCurrency);
-                }
-                unset($requestData['templateData']['MinimumAmountDue']);
-
-                if(isset($requestData['templateData']['TotalAmount']) && count(array_filter($requestData['templateData']['TotalAmount'])) > 0){
-                    $TemplateTotalAmountCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['TotalAmount']), $TemplateTotalAmountCurrency);
-                    $invoiceTemplateData->setTotalAmount($TemplateTotalAmountCurrency);
-                }
-                unset($requestData['templateData']['TotalAmount']);
-                $this->setArrayToMethods(array_filter($requestData['templateData']), $invoiceTemplateData);
-            }
-
-            $templateDataCcInfo = isset($requestData['TemplateDataCcInfo']) ? trim($requestData['TemplateDataCcInfo']) : '';
-            if(!empty($templateDataCcInfo)){
-                $invoiceTemplateData->addCcInfo($templateDataCcInfo);
-            }
-
-            if(isset($requestData['templateDiscount']) && count(array_filter($requestData['templateDiscount'])) > 0){
-                $templateDiscountCost = new Cost();
-                $this->setArrayToMethods(array_filter($requestData['templateDiscount']), $templateDiscountCost);
-                $invoiceTemplateData->setDiscount($templateDiscountCost);
-            }
-
-            if(isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0){
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoiceTemplateData->setPaymentTerm($PaymentTerm);
-            }
-
-            if(isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0){
-                $attachment = new FileAttachment();
-                $this->setArrayToMethods(array_filter($requestData['attachments']), $attachment);
-                $invoiceTemplateData->setAttachments(array($attachment));
-            }
-
-            // ### Template Settings
-            $displayPreferences = new TemplateSettingsMetadata();
-            if(isset($requestData['TemplateSettingsMetadata']) && count(array_filter($requestData['TemplateSettingsMetadata']))>0){
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettingsMetadata']), $displayPreferences);
-            }
-
-            $settingDate = new TemplateSettings();
-            if(isset($requestData['TemplateSettings']) && count(array_filter($requestData['TemplateSettings']))>0){
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettings']), $settingDate);
-            }
-
-            if(count(array_filter((array)$displayPreferences)) > 0){
-                $settingDate->setDisplayPreference($displayPreferences);
-            }
-            // ### Template
-            $invoiceTemplate = new Template();
-            $invoiceTemplate->setTemplateId($templateId);
-            if(isset($requestData['Template']) && count(array_filter($requestData['Template'])) > 0){
-                $this->setArrayToMethods(array_filter($requestData['Template']), $invoiceTemplate);
-            }
-
-            if(count(array_filter((array)$invoiceTemplateData)) > 0){
-                $invoiceTemplate->setTemplateData($invoiceTemplateData);
-            }
-
-            if(count(array_filter((array)$settingDate)) > 0){
-                $invoiceTemplate->addSetting($settingDate);
-            }
-
-            $requestArray = clone $invoiceTemplate;
-            $invoiceTemplate->update($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE_TEMPLATE'] = $invoiceTemplate->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$invoiceTemplate->toJSON();  
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-}
-
diff --git a/src/angelleye/PayPal/rest/invoice/InvoiceAPIv2.php b/src/angelleye/PayPal/rest/invoice/InvoiceAPIv2.php
deleted file mode 100644
index 966bed5e..00000000
--- a/src/angelleye/PayPal/rest/invoice/InvoiceAPIv2.php
+++ /dev/null
@@ -1,1298 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
- */
-
-use PayPal\Api\Address;
-use PayPal\Api\Amount;
-use PayPal\Api\BillingInfo;
-use PayPal\Api\CancelNotification;
-use PayPal\Api\Cost;
-use PayPal\Api\Currency;
-use PayPal\Api\FileAttachment;
-use PayPal\Api\Invoice;
-use PayPal\Api\InvoiceAddress;
-use PayPal\Api\InvoiceItem;
-use PayPal\Api\MerchantInfo;
-use PayPal\Api\Notification;
-use PayPal\Api\PaymentTerm;
-use PayPal\Api\PaymentDetail;
-use PayPal\Api\Phone;
-use PayPal\Api\Participant;
-use PayPal\Api\RefundDetail;
-use PayPal\Api\Search;
-use PayPal\Api\ShippingInfo;
-use PayPal\Api\ShippingCost;
-use PayPal\Api\Tax;
-use PayPal\Api\Template;
-use PayPal\Api\Templates;
-use PayPal\Api\TemplateData;
-use PayPal\Api\TemplateSettings;
-use PayPal\Api\TemplateSettingsMetadata;
-use \angelleye\PayPal\RestClass;
-use \angelleye\PayPal\InvoicingClass;
-
-/**
- * InvoiceAPI.
- * This class is responsible for Invoice APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class InvoiceAPIv2 extends RestClass
-{
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-     * Constructor
-     *
-     * @access	public
-     * @param	mixed[]	$configArray Array structure providing config data
-     * @return	void
-     */
-    public function __construct($configArray)
-    {
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     *  Creates an invoice. Include invoice details including merchant information in the request.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function CreateInvoice($requestData, $third_party = false, $refesh_token = '')
-    {
-        try {
-            $invoice = new InvoicingClass();
-
-            // ### Setting Merchant info to invoice object.
-            // ### Start
-            $MerchantInfo = new MerchantInfo();
-            if (isset($requestData['merchantInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantInfo']), $MerchantInfo);
-                if (isset($requestData['merchantPhone'])) {
-                    $merchantPhone = new Phone();
-                    $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                if (isset($requestData['merchantAddress'])) {
-                    $merchantAddress = new Address();
-                    $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoice->setMerchantInfo($MerchantInfo);
-            }
-            // ### End
-
-            // ### Setting cc_info
-            // ### Start
-            $Participant = new Participant();
-            if (isset($requestData['ccInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['ccInfo']), $Participant);
-                $participantArray = $this->checkEmptyObject((array)$Participant);
-                if (!empty($participantArray)) {
-                    $invoice->setCcInfo(array($Participant));
-                }
-            }
-            // ### End
-
-            // ### Setting Minimum Amount Due
-            // ### Start                            
-            $MinAmountCurrency = new Currency();
-            if (isset($requestData['MinimumAmountDue'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['MinimumAmountDue']), $MinAmountCurrency);
-            }
-            $MinAmountCurrencyArray = $this->checkEmptyObject((array)$MinAmountCurrency);
-            if (!empty($MinAmountCurrencyArray)) {
-                $invoice->setMinimumAmountDue($MinAmountCurrency);
-            }
-            // ### End
-
-            // ### Setting Billing Info to invoice object. 
-            // ### Start
-            $BillingInfo = new BillingInfo();
-            if (isset($requestData['billingInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfo']), $BillingInfo);
-            }
-            if (isset($requestData['billingInfoAddress'])) {
-                $InvoiceAddress = new InvoiceAddress();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoAddress']), $InvoiceAddress);
-                $BillingInfo->setAddress($InvoiceAddress);
-            }
-            if (isset($requestData['billingInfoPhone'])) {
-                $billingPhone = new Phone();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoPhone']), $billingPhone);
-                $BillingInfo->setPhone($billingPhone);
-            }
-
-            $BillingInfoArray = $this->checkEmptyObject((array)$BillingInfo);
-            if (!empty($BillingInfoArray)) {
-                $invoice->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-            // ### Add items in Invoice object.
-            // ### Start.    
-            if (isset($requestData['itemArray'])) {
-                $itemArray = array();
-                foreach ($requestData['itemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if (isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0) {
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->unit_amount = $ItemCurrency;
-                    }
-                    unset($item['UnitPrice']);
-                    if (isset($item['Tax']) && count(array_filter($item['Tax'])) > 0) {
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-                    if (isset($item['Discount']) && count(array_filter($item['Discount'])) > 0) {
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                    array_push($itemArray, $InvoiceItem);
-                }
-                $itemArrayData = $this->checkEmptyObject($itemArray);
-                if (!empty($itemArrayData)) {
-                    $invoice->setItems($itemArray);
-                }
-            }
-            // ### END
-
-            // #### Final Discount
-            // You can add final discount to the invoice as shown below. You could either use "percent" or "value" when providing the discount
-
-            if (isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Percent') {
-                $FinalDiscountCost = new Cost();
-                $FinalDiscountCost->setPercent($requestData['finalDiscountForInvoice']['Percent']);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-            if (isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Amount') {
-                $FinalDiscountCost = new Cost();
-                $discountCurrency = new Currency();
-                $discountCurrency->setCurrency($requestData['finalDiscountForInvoice']['Amount']['Currency']);
-                $discountCurrency->setValue($requestData['finalDiscountForInvoice']['Amount']['Value']);
-                $FinalDiscountCost->setAmount($discountCurrency);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-
-            if (isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0) {
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoice->setPaymentTerm($PaymentTerm);
-            }
-
-            // ### Shipping Information
-            // ### Start
-            $ShippingInfo = new ShippingInfo();
-            if (isset($requestData['shippingInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfo']), $ShippingInfo);
-            }
-            if (isset($requestData['shippingInfoPhone'])) {
-                $ShippingInfoPhone = new Phone();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                $ShippingInfo->setPhone($ShippingInfoPhone);
-            }
-            if (isset($requestData['shippingInfoAddress'])) {
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-            }
-
-            $shippingInfoArray = $this->checkEmptyObject((array)$ShippingInfo);
-            if (!empty($shippingInfoArray)) {
-                $invoice->setShippingInfo($ShippingInfo);
-            }
-            if (isset($requestData['invoiceData'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['invoiceData']), $invoice);
-            }
-
-            if (isset($requestData['shippingCost']['type']) && $requestData['shippingCost']['type'] == 'Amount') {
-                $shippingCurrency = new Currency();
-                $shippingCurrency->setCurrency($requestData['shippingCost']['Amount']['Currency']);
-                $shippingCurrency->setValue($requestData['shippingCost']['Amount']['Value']);
-                $ShippingCost = new ShippingCost();
-                $ShippingCost->setAmount($shippingCurrency);
-                $invoice->setShippingCost($ShippingCost);
-            }
-
-
-            if (isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0) {
-                foreach ($requestData['attachments'] as $value) {
-                    $attachment = new FileAttachment();
-                    $attachment->setName($value['Name']);
-                    $attachment->setUrl($value['url']);
-                    $invoice->setAttachments(array($attachment));
-                }
-            }
-            echo '
';
-            print_r($invoice);
-            exit;
-            // ### Create Invoice
-            // Create an invoice by calling the invoice->create() method
-            if ($third_party === true  && !empty($refesh_token)) {
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $requestArray = clone $invoice;
-            $invoice->create($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray->toJSON();
-            $returnArray['RAWRESPONSE'] = $invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Lists some or all merchant invoices. Filters the response by any specified optional query string parameters.
-     *
-     * @param Array $params
-     * @return Array|Object
-     */
-    public function ListInvoice($params, $third_party = false, $refesh_token = '')
-    {
-        try {
-            $apiContext = $this->_api_context;
-            if ($third_party === true  && !empty($refesh_token)) {
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $invoices = InvoicingClass::getAll(array_filter($params), $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICES'] = $invoices->toArray();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Gets the details for a specified invoice, by ID.
-     *
-     * @param string $invoiceId
-     * @return Array|Object
-     */
-    public function GetInvoice($invoiceId)
-    {
-        try {
-            $invoice = InvoicingClass::get($invoiceId, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST'] = '{id:' . $invoiceId . '}';
-            $returnArray['RAWRESPONSE'] = $invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Creates third party invoice on someone else's behalf.
-     * This requires using `Obtain User's Consent` to fetch the refresh token of the third party merchant.     
-     *  
-     * @param string $invoiceId
-     * @param string $refreshToken
-     * @return Array|Object
-     */
-    public function GetThirdPartyInvoice($invoiceId, $refreshToken)
-    {
-        try {
-            $apiContext = $this->_api_context;
-            $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken);
-            $invoice = InvoicingClass::get($invoiceId, $apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST'] = '{id:' . $invoiceId . '}';
-            $returnArray['RAWRESPONSE'] = $invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Cancels an invoice, by ID.
-     *
-     * @param Array $cancelNotification
-     * @param string $InvoiceID
-     * @return boolean
-     */
-    public function CancelInvoice($cancelNotification, $InvoiceID, $third_party = false, $refesh_token = '')
-    {
-        try {
-
-            $notify = array_filter($cancelNotification);
-            $invoice = new InvoicingClass();
-            $invoice->setId($InvoiceID);
-            if ($third_party === true  && !empty($refesh_token)) {
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $requestArray = clone $invoice;
-            $cancelStatus = $invoice->cancel($notify, $this->_api_context);
-
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CANCEL_STATUS'] = $cancelStatus;
-            $returnArray['RAWREQUEST'] = $requestArray->toJSON();
-            $returnArray['RAWRESPONSE'] = $cancelStatus;
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Marks the status of a specified invoice, by ID, as refunded.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function RecordRefund($requestData, $third_party = false, $refesh_token = '')
-    {
-        try {
-            $invoice  = new InvoicingClass();
-            $invoice->setId($requestData['invoiceId']);
-            if ($third_party === true  && !empty($refesh_token)) {
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $refund = new RefundDetail();
-            if (isset($requestData['refundDetail'])) {
-                $this->setArrayToMethods($requestData['refundDetail'], $refund);
-            }
-
-            if (isset($requestData['amount']) && count(array_filter($requestData['amount'])) > 0) {
-                $amt = new Currency(json_encode($requestData['amount']));
-                $refund->setAmount($amt);
-            }
-            $requestArray = clone $invoice;
-            $refundStatus = $invoice->recordRefund($refund, $this->_api_context);
-            $invoice = InvoicingClass::get($requestData['invoiceId'], $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REFUND_STATUS'] = $refundStatus;
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray;
-            $returnArray['RAWRESPONSE'] = $invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Sends a reminder to the payer about an invoice, by ID.
-     *
-     * @param Array $remindNotification
-     * @param string $InvoiceID
-     * @return Array|Object
-     */
-    public function RemindInvoice($remindNotification, $InvoiceID, $third_party = false, $refesh_token = '')
-    {
-        try {
-            $apiContext = $this->_api_context;
-            if ($third_party === true  && !empty($refesh_token)) {
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $invoice  = new InvoicingClass();
-            $invoice->setId($InvoiceID);
-            $notify = new Notification();
-            $this->setArrayToMethods(array_filter($remindNotification), $notify);
-            $remindStatus = $invoice->remind($notify, $apiContext);
-            $requestArray = clone $invoice;
-            $invoice = InvoicingClass::get($InvoiceID, $apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REMIND_STATUS'] = $remindStatus;
-            $returnArray['REMIND_INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray;
-            $returnArray['RAWRESPONSE'] = $invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Generate a QR code for an invoice by passing the invoice ID.
-     *
-     * @param Array $parameters
-     * @param string $InvoiceID
-     * @param string $path
-     * @return Array|Object
-     */
-    public function RetrieveQRCode($parameters, $InvoiceID, $path, $third_party = false, $refesh_token = '')
-    {
-
-        try {
-            $apiContext = $this->_api_context;
-            if ($third_party === true  && !empty($refesh_token)) {
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $image = InvoicingClass::qrCode($InvoiceID, array_filter($parameters), $apiContext);
-            $path = $image->saveToFile($path);
-            $returnArray['RESULT'] = 'Success';
-            return array('Image' => $image->getImage());
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Searches for an invoice or invoices. Include a search object that specifies your search criteria in the request.
-     *
-     * @param Array $parameters
-     * @return Array|Object
-     */
-    public function SearchInvoices($parameters, $third_party = false, $refesh_token = '')
-    {
-
-        try {
-            $apiContext = $this->_api_context;
-            if ($third_party === true  && !empty($refesh_token)) {
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $search = new Search(json_encode(array_filter($parameters)));
-            $invoices = InvoicingClass::search($search, $apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICES'] = $invoices->toArray();
-            $returnArray['RAWREQUEST'] = json_encode(array_filter($parameters));
-            $returnArray['RAWRESPONSE'] = $invoices->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Fully updates an invoice, by ID.
-     *
-     * @param Array|Object $requestData
-     * @return Array|Object
-     */
-    public function UpdateInvoice($requestData, $third_party = false, $refesh_token = '')
-    {
-
-        try {
-            $invoice = new InvoicingClass();
-            $invoice->setId($requestData['InvoiceID']);
-            // ### Setting Merchant info to invoice object.
-            // ### Start
-            $MerchantInfo = new MerchantInfo();
-            if (isset($requestData['merchantInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantInfo']), $MerchantInfo);
-                if (isset($requestData['merchantPhone'])) {
-                    $merchantPhone = new Phone();
-                    $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                if (isset($requestData['merchantAddress'])) {
-                    $merchantAddress = new Address();
-                    $this->setArrayToMethods($this->checkEmptyObject($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoice->setMerchantInfo($MerchantInfo);
-            }
-            // ### End
-
-            // ### Setting cc_info
-            // ### Start
-            $Participant = new Participant();
-            if (isset($requestData['ccInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['ccInfo']), $Participant);
-                $participantArray = $this->checkEmptyObject((array)$Participant);
-                if (!empty($participantArray)) {
-                    $invoice->setCcInfo(array($Participant));
-                }
-            }
-            // ### End
-
-            // ### Setting Minimum Amount Due
-            // ### Start
-            $MinAmountCurrency = new Currency();
-            if (isset($requestData['MinimumAmountDue'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['MinimumAmountDue']), $MinAmountCurrency);
-            }
-            $MinAmountCurrencyArray = $this->checkEmptyObject((array)$MinAmountCurrency);
-            if (!empty($MinAmountCurrencyArray)) {
-                $invoice->setMinimumAmountDue($MinAmountCurrency);
-            }
-            // ### End
-
-            // ### Setting Billing Info to invoice object.
-            // ### Start
-            $BillingInfo = new BillingInfo();
-            if (isset($requestData['billingInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfo']), $BillingInfo);
-            }
-            if (isset($requestData['billingInfoAddress'])) {
-                $InvoiceAddress = new InvoiceAddress();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoAddress']), $InvoiceAddress);
-                $BillingInfo->setAddress($InvoiceAddress);
-            }
-            if (isset($requestData['billingInfoPhone'])) {
-                $billingPhone = new Phone();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['billingInfoPhone']), $billingPhone);
-                $BillingInfo->setPhone($billingPhone);
-            }
-
-            $BillingInfoArray = $this->checkEmptyObject((array)$BillingInfo);
-            if (!empty($BillingInfoArray)) {
-                $invoice->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-            // ### Add items in Invoice object.
-            // ### Start.
-            if (isset($requestData['itemArray'])) {
-
-                $itemArray = array();
-                foreach ($requestData['itemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if (isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0) {
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->setUnitPrice($ItemCurrency);
-                    }
-                    unset($item['UnitPrice']);
-                    if (isset($item['Tax']) && count(array_filter($item['Tax'])) > 0) {
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-                    if (isset($item['Discount']) && count(array_filter($item['Discount'])) > 0) {
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                    array_push($itemArray, $InvoiceItem);
-                }
-                $itemArrayData = $this->checkEmptyObject($itemArray);
-                if (!empty($itemArrayData)) {
-                    $invoice->setItems($itemArray);
-                }
-            }
-            // ### END
-
-            // #### Final Discount
-            // You can add final discount to the invoice as shown below. You could either use "percent" or "value" when providing the discount
-
-            if (isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Percent') {
-                $FinalDiscountCost = new Cost();
-                $FinalDiscountCost->setPercent($requestData['finalDiscountForInvoice']['Percent']);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-            if (isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Amount') {
-                $FinalDiscountCost = new Cost();
-                $discountCurrency = new Currency();
-                $discountCurrency->setCurrency($requestData['finalDiscountForInvoice']['Amount']['Currency']);
-                $discountCurrency->setValue($requestData['finalDiscountForInvoice']['Amount']['Value']);
-                $FinalDiscountCost->setAmount($discountCurrency);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-            if (isset($requestData['finalDiscountForInvoice']) && $requestData['finalDiscountForInvoice']['type']  == 'Amount') {
-                $FinalDiscountCost = new Cost();
-                $discountCurrency = new Currency();
-                $discountCurrency->setCurrency($requestData['finalDiscountForInvoice']['Amount']['Currency']);
-                $discountCurrency->setValue($requestData['finalDiscountForInvoice']['Amount']['Value']);
-                $FinalDiscountCost->setAmount($discountCurrency);
-                $invoice->setDiscount($FinalDiscountCost);
-            }
-
-            if (isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0) {
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoice->setPaymentTerm($PaymentTerm);
-            }
-
-            // ### Shipping Information
-            // ### Start
-            $ShippingInfo = new ShippingInfo();
-            if (isset($requestData['shippingInfo'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfo']), $ShippingInfo);
-            }
-            if (isset($requestData['shippingInfoPhone'])) {
-                $ShippingInfoPhone = new Phone();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                $ShippingInfo->setPhone($ShippingInfoPhone);
-            }
-            if (isset($requestData['shippingInfoAddress'])) {
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-            }
-
-            $shippingInfoArray = $this->checkEmptyObject((array)$ShippingInfo);
-            if (!empty($shippingInfoArray)) {
-                $invoice->setShippingInfo($ShippingInfo);
-            }
-            if (isset($requestData['invoiceData'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['invoiceData']), $invoice);
-            }
-
-            if (isset($requestData['shippingCost']['type']) && $requestData['shippingCost']['type'] == 'Amount') {
-                $shippingCurrency = new Currency();
-                $this->setArrayToMethods(array_filter($requestData['shippingCost']['Currency']), $shippingCurrency);
-                $ShippingCost = new ShippingCost();
-                $ShippingCost->setAmount($shippingCurrency);
-                $invoice->setShippingCost($ShippingCost);
-            }
-            if (isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0) {
-                foreach ($requestData['attachments'] as $key => $value) {
-                    $attachment = new FileAttachment();
-                    $attachment->setName($value['Name']);
-                    $attachment->setUrl($value['Url']);
-                    $invoice->setAttachments(array($attachment));
-                }
-            }
-            if (isset($requestData['shippingCost']['type']) && $requestData['shippingCost']['type'] == 'Amount') {
-                $shippingCurrency = new Currency();
-                $shippingCurrency->setCurrency($requestData['shippingCost']['Amount']['Currency']);
-                $shippingCurrency->setValue($requestData['shippingCost']['Amount']['Value']);
-                $ShippingCost = new ShippingCost();
-                $ShippingCost->setAmount($shippingCurrency);
-                $invoice->setShippingCost($ShippingCost);
-            }
-            $this->setArrayToMethods(array_filter($requestData['invoiceData']), $invoice);
-
-            if ($third_party === true  && !empty($refesh_token)) {
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $requestArray = clone $invoice;
-            $invoice->update($this->_api_context);
-            $invoice = InvoicingClass::get($invoice->getId(), $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE'] = $invoice->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray;
-            $returnArray['RAWRESPONSE'] = $invoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Sends an invoice, by ID, to a customer. 
-     *
-     * @param string $invoiceId
-     * @param boolean $third_party
-     * @param  string $refresh_token
-     * @return Array|Object
-     */
-    public function SendInvoice($invoiceId, $third_party = false, $refresh_token = '')
-    {
-        try {
-            $invoice = new InvoicingClass();
-            $invoice->setId($invoiceId);
-            if ($third_party === true  && !empty($refresh_token)) {
-                $invoice->updateAccessToken($refresh_token, $this->_api_context);
-            }
-            $sendStatus = $invoice->send($this->_api_context);
-            $Getinvoice = InvoicingClass::get($invoice->getId(), $this->_api_context);
-
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['SEND_STATUS'] = $sendStatus;
-            $returnArray['INVOICE'] = $Getinvoice->toArray();
-            $returnArray['RAWREQUEST'] = '{id:' . $invoiceId . '}';
-            $returnArray['RAWRESPONSE'] = $Getinvoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Deletes invoices in the DRAFT or SCHEDULED state, by ID. 
-     *
-     * @param string $invoiceId
-     * @return Array|Object
-     */
-    public function DeleteInvoice($invoiceId, $third_party = false, $refesh_token = '')
-    {
-
-        try {
-            $invoice = new InvoicingClass();
-            $invoice->setId($invoiceId);
-            if ($third_party === true  && !empty($refesh_token)) {
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $deleteStatus = $invoice->delete($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DELETE_STATUS'] = $deleteStatus;
-            $returnArray['RAWREQUEST'] = '{id:' . $invoiceId . '}';
-            $returnArray['RAWRESPONSE'] = $deleteStatus;
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Generates the next invoice number that is available to the merchant.
-     * The next invoice number uses the prefix and suffix from the last invoice number and increments the number by one.
-     *
-     * @return Array|Object
-     */
-    public function GetNextInvoiceNumber($third_party = false, $refesh_token = '')
-    {
-        try {
-            $apiContext = $this->_api_context;
-            if ($third_party === true  && !empty($refesh_token)) {
-                $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refesh_token);
-            }
-            $number = InvoicingClass::generateNumber($apiContext);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE_NUMBER'] = $number->toArray();
-            $returnArray['RAWREQUEST'] = '';
-            $returnArray['RAWRESPONSE'] = $number->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     *Marks the status of a specified invoice, by ID, as paid.
-     *
-     * @param string $invoiceId
-     * @param Array $record
-     * @param Array $amount
-     * @return Array|Object
-     */
-    public function RecordPayment($invoiceId, $record, $amount, $third_party = false, $refesh_token = '')
-    {
-        try {
-            $invoice = new InvoicingClass();
-            $invoice->setId($invoiceId);
-            if ($third_party === true  && !empty($refesh_token)) {
-                $invoice->updateAccessToken($refesh_token, $this->_api_context);
-            }
-            $PaymentDetail = new PaymentDetail();
-            $this->setArrayToMethods(array_filter($record), $PaymentDetail);
-
-            if (count(array_filter($amount)) > 0) {
-                $amt = new Currency(json_encode($amount));
-                $PaymentDetail->setAmount($amt);
-            }
-
-            $recordStatus = $invoice->recordPayment($PaymentDetail, $this->_api_context);
-
-            $returnInvoice = InvoicingClass::get($invoiceId, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['RECORD_STATUS'] = $recordStatus;
-            $returnArray['INVOICE'] = $returnInvoice->toArray();
-            $returnArray['RAWREQUEST'] = '{id:' . $invoiceId . '}';
-            $returnArray['RAWRESPONSE'] = $returnInvoice->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Creates an invoice template.
-     *
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function CreateInvoiceTemplate($requestData)
-    {
-
-        try {
-            $invoiceTemplateData = new TemplateData();
-
-            /**
-             * Setting Items in Invoice Template
-             */
-            if (isset($requestData['InvoiceItemArray'])) {
-                $itemArray = array();
-
-                foreach ($requestData['InvoiceItemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if (isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0) {
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->setUnitPrice($ItemCurrency);
-                    }
-                    unset($item['UnitPrice']);
-
-                    if (isset($item['Tax']) && count(array_filter($item['Tax'])) > 0) {
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-
-                    if (isset($item['Discount']) && count(array_filter($item['Discount'])) > 0) {
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    if (count(array_filter($item)) > 0) {
-                        $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                        array_push($itemArray, $InvoiceItem);
-                        $invoiceTemplateData->addItem($InvoiceItem);
-                    }
-                }
-            }
-
-
-            // ### Setting Merchant info to invoice template object.
-            // ### Start
-            if (isset($requestData['merchantInfo'])) {
-                $MerchantInfo = new MerchantInfo();
-                if (isset($requestData['merchantInfo']) && count(array_filter($requestData['merchantInfo'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['merchantInfo']), $MerchantInfo);
-                }
-                $merchantPhone = new Phone();
-                if (isset($requestData['merchantPhone']) && count(array_filter($requestData['merchantPhone'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                $merchantAddress = new Address();
-                if (isset($requestData['merchantAddress']) && count(array_filter($requestData['merchantAddress'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoiceTemplateData->setMerchantInfo($MerchantInfo);
-            }
-
-
-
-            // ### End
-
-            // ### Setting Billing Info to invoice object. 
-            // ### Start
-
-            if (isset($requestData['billingInfo'])) {
-                $BillingInfo = new BillingInfo();
-                if (isset($requestData['billingInfo']) && count(array_filter($requestData['billingInfo'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['billingInfo']), $BillingInfo);
-                }
-
-                $InvoiceAddress = new InvoiceAddress();
-                if (isset($requestData['billingInfoAddress']) && count(array_filter($requestData['billingInfoAddress'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoAddress']), $InvoiceAddress);
-                    $BillingInfo->setAddress($InvoiceAddress);
-                }
-
-                $billingPhone = new Phone();
-                if (count(array_filter($requestData['billingInfoPhone'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoPhone']), $billingPhone);
-                    $BillingInfo->setPhone($billingPhone);
-                }
-                $invoiceTemplateData->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-
-            // ### Shipping Information
-            // ### Start
-
-            if (isset($requestData['shippingInfo'])) {
-                $ShippingInfo = new ShippingInfo();
-                $this->setArrayToMethods(array_filter($requestData['shippingInfo']), $ShippingInfo);
-
-                $ShippingInfoPhone = new Phone();
-                if (isset($requestData['shippingInfoPhone']) && count(array_filter($requestData['shippingInfoPhone'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                    $ShippingInfo->setPhone($ShippingInfoPhone);
-                }
-
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                if (isset($requestData['shippingInfoAddress']) && count(array_filter($requestData['shippingInfoAddress'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                    $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-                }
-                $invoiceTemplateData->setShippingInfo($ShippingInfo);
-            }
-            if (isset($requestData['templateData'])) {
-                if (isset($requestData['templateData']['MinimumAmountDue']) && count(array_filter($requestData['templateData']['MinimumAmountDue'])) > 0) {
-                    $TemplateMinimumAmountDueCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['MinimumAmountDue']), $TemplateMinimumAmountDueCurrency);
-                    $invoiceTemplateData->setMinimumAmountDue($TemplateMinimumAmountDueCurrency);
-                }
-                unset($requestData['templateData']['MinimumAmountDue']);
-
-                if (isset($requestData['templateData']['TotalAmount']) && count(array_filter($requestData['templateData']['TotalAmount'])) > 0) {
-                    $TemplateTotalAmountCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['TotalAmount']), $TemplateTotalAmountCurrency);
-                    $invoiceTemplateData->setTotalAmount($TemplateTotalAmountCurrency);
-                }
-                unset($requestData['templateData']['TotalAmount']);
-                $this->setArrayToMethods(array_filter($requestData['templateData']), $invoiceTemplateData);
-            }
-
-            $templateDataCcInfo = isset($requestData['TemplateDataCcInfo']) ? trim($requestData['TemplateDataCcInfo']) : '';
-            if (!empty($templateDataCcInfo)) {
-                $invoiceTemplateData->addCcInfo($templateDataCcInfo);
-            }
-
-            if (isset($requestData['templateDiscount']) && count(array_filter($requestData['templateDiscount'])) > 0) {
-                $templateDiscountCost = new Cost();
-                $this->setArrayToMethods(array_filter($requestData['templateDiscount']), $templateDiscountCost);
-                $invoiceTemplateData->setDiscount($templateDiscountCost);
-            }
-
-            if (isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0) {
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoiceTemplateData->setPaymentTerm($PaymentTerm);
-            }
-
-            if (isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0) {
-                $attachment = new FileAttachment();
-                $this->setArrayToMethods(array_filter($requestData['attachments']), $attachment);
-                $invoiceTemplateData->setAttachments(array($attachment));
-            }
-
-            // ### Template Settings    
-            $displayPreferences = new TemplateSettingsMetadata();
-            if (isset($requestData['TemplateSettingsMetadata']) && count(array_filter($requestData['TemplateSettingsMetadata'])) > 0) {
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettingsMetadata']), $displayPreferences);
-            }
-
-            $settingDate = new TemplateSettings();
-            if (isset($requestData['TemplateSettings']) && count(array_filter($requestData['TemplateSettings'])) > 0) {
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettings']), $settingDate);
-            }
-
-            if (count(array_filter((array)$displayPreferences)) > 0) {
-                $settingDate->setDisplayPreference($displayPreferences);
-            }
-
-            // ### Template
-            $invoiceTemplate = new Template();
-            if (isset($requestData['Template']) && count(array_filter($requestData['Template'])) > 0) {
-                $this->setArrayToMethods(array_filter($requestData['Template']), $invoiceTemplate);
-            }
-
-            if (count(array_filter((array)$invoiceTemplateData)) > 0) {
-                $invoiceTemplate->setTemplateData($invoiceTemplateData);
-            }
-
-            if (count(array_filter((array)$settingDate)) > 0) {
-                $invoiceTemplate->addSetting($settingDate);
-            }
-            $requestArray = clone $invoiceTemplate;
-            $invoiceTemplate->create($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['TEMPLATE'] = $invoiceTemplate->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray->toJSON();
-            $returnArray['RAWRESPONSE'] = $invoiceTemplate->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Deletes a template, by ID.
-     *
-     * @param string $template_id
-     * @return Array|Object
-     */
-    public function DeleteInvoiceTemplate($template_id)
-    {
-        try {
-            $template = new Template();
-            $template->setTemplateId($template_id);
-            $deleteStatus = $template->delete($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DELETE_STATUS'] = $deleteStatus;
-            $returnArray['RAWREQUEST'] = '{id:' . $template_id . '}';
-            $returnArray['RAWRESPONSE'] = $deleteStatus;
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Lists merchant-created templates with associated details
-     *
-     * @param Array $fields
-     * @return Array|Object
-     */
-    public function GetAllInvoiceTemplates($fields)
-    {
-
-        try {
-            $templates = Templates::getAll($fields, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE_TEMPLATES'] = $templates->toArray();
-            $returnArray['RAWREQUEST'] = json_encode($fields);
-            $returnArray['RAWRESPONSE'] = $templates->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for a template, by ID.
-     *
-     * @param string $templateId
-     * @return Array|Object
-     */
-    public function GetInvoiceTemplate($templateId)
-    {
-        try {
-            $template = Template::get($templateId, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['TEMPLATE'] = $template->toArray();
-            $returnArray['RAWREQUEST'] = '{id:' . $templateId . '}';
-            $returnArray['RAWRESPONSE'] = $template->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Updates a template, by ID.
-     *
-     * @param string  $templateId
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function UpdateInvoiceTemplate($templateId, $requestData)
-    {
-        try {
-            $invoiceTemplateData = new TemplateData();
-            /**
-             * Setting Items in Invoice Template
-             */
-            if (isset($requestData['InvoiceItemArray'])) {
-                $itemArray = array();
-
-                foreach ($requestData['InvoiceItemArray'] as $item) {
-                    $InvoiceItem = new InvoiceItem();
-
-                    if (isset($item['UnitPrice']) && count(array_filter($item['UnitPrice'])) > 0) {
-                        $ItemCurrency = new Currency();
-                        $this->setArrayToMethods(array_filter($item['UnitPrice']), $ItemCurrency);
-                        $InvoiceItem->setUnitPrice($ItemCurrency);
-                    }
-                    unset($item['UnitPrice']);
-
-                    if (isset($item['Tax']) && count(array_filter($item['Tax'])) > 0) {
-                        $ItemTax = new Tax();
-                        $this->setArrayToMethods(array_filter($item['Tax']), $ItemTax);
-                        $InvoiceItem->setTax($ItemTax);
-                    }
-                    unset($item['Tax']);
-
-                    if (isset($item['Discount']) && count(array_filter($item['Discount'])) > 0) {
-                        $ItemCost = new Cost();
-                        $this->setArrayToMethods(array_filter($item['Discount']), $ItemCost);
-                        $InvoiceItem->setDiscount($ItemCost);
-                    }
-                    unset($item['Discount']);
-
-                    if (count(array_filter($item)) > 0) {
-                        $this->setArrayToMethods(array_filter($item), $InvoiceItem);
-                        array_push($itemArray, $InvoiceItem);
-                        $invoiceTemplateData->addItem($InvoiceItem);
-                    }
-                }
-            }
-
-
-            // ### Setting Merchant info to invoice template object.
-            // ### Start
-            if (isset($requestData['merchantInfo'])) {
-                $MerchantInfo = new MerchantInfo();
-                if (isset($requestData['merchantInfo']) && count(array_filter($requestData['merchantInfo'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['merchantInfo']), $MerchantInfo);
-                }
-                $merchantPhone = new Phone();
-                if (isset($requestData['merchantPhone']) && count(array_filter($requestData['merchantPhone'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['merchantPhone']), $merchantPhone);
-                    $MerchantInfo->setPhone($merchantPhone);
-                }
-                $merchantAddress = new Address();
-                if (isset($requestData['merchantAddress']) && count(array_filter($requestData['merchantAddress'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['merchantAddress']), $merchantAddress);
-                    $MerchantInfo->setAddress($merchantAddress);
-                }
-                $invoiceTemplateData->setMerchantInfo($MerchantInfo);
-            }
-
-            // ### End
-
-            // ### Setting Billing Info to invoice object.
-            // ### Start
-
-            if (isset($requestData['billingInfo'])) {
-                $BillingInfo = new BillingInfo();
-                if (isset($requestData['billingInfo']) && count(array_filter($requestData['billingInfo'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['billingInfo']), $BillingInfo);
-                }
-
-                $InvoiceAddress = new InvoiceAddress();
-                if (isset($requestData['billingInfoAddress']) && count(array_filter($requestData['billingInfoAddress'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoAddress']), $InvoiceAddress);
-                    $BillingInfo->setAddress($InvoiceAddress);
-                }
-
-                $billingPhone = new Phone();
-                if (count(array_filter($requestData['billingInfoPhone'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['billingInfoPhone']), $billingPhone);
-                    $BillingInfo->setPhone($billingPhone);
-                }
-                $invoiceTemplateData->setBillingInfo(array($BillingInfo));
-            }
-            //End
-
-
-            // ### Shipping Information
-            // ### Start
-
-            if (isset($requestData['shippingInfo'])) {
-                $ShippingInfo = new ShippingInfo();
-                $this->setArrayToMethods(array_filter($requestData['shippingInfo']), $ShippingInfo);
-
-                $ShippingInfoPhone = new Phone();
-                if (isset($requestData['shippingInfoPhone']) && count(array_filter($requestData['shippingInfoPhone'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoPhone']), $ShippingInfoPhone);
-                    $ShippingInfo->setPhone($ShippingInfoPhone);
-                }
-
-                $ShippingInfoInvoiceAddress = new InvoiceAddress();
-                if (isset($requestData['shippingInfoAddress']) && count(array_filter($requestData['shippingInfoAddress'])) > 0) {
-                    $this->setArrayToMethods(array_filter($requestData['shippingInfoAddress']), $ShippingInfoInvoiceAddress);
-                    $ShippingInfo->setAddress($ShippingInfoInvoiceAddress);
-                }
-                $invoiceTemplateData->setShippingInfo($ShippingInfo);
-            }
-            if (isset($requestData['templateData'])) {
-                if (isset($requestData['templateData']['MinimumAmountDue']) && count(array_filter($requestData['templateData']['MinimumAmountDue'])) > 0) {
-                    $TemplateMinimumAmountDueCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['MinimumAmountDue']), $TemplateMinimumAmountDueCurrency);
-                    $invoiceTemplateData->setMinimumAmountDue($TemplateMinimumAmountDueCurrency);
-                }
-                unset($requestData['templateData']['MinimumAmountDue']);
-
-                if (isset($requestData['templateData']['TotalAmount']) && count(array_filter($requestData['templateData']['TotalAmount'])) > 0) {
-                    $TemplateTotalAmountCurrency = new Currency();
-                    $this->setArrayToMethods(array_filter($requestData['templateData']['TotalAmount']), $TemplateTotalAmountCurrency);
-                    $invoiceTemplateData->setTotalAmount($TemplateTotalAmountCurrency);
-                }
-                unset($requestData['templateData']['TotalAmount']);
-                $this->setArrayToMethods(array_filter($requestData['templateData']), $invoiceTemplateData);
-            }
-
-            $templateDataCcInfo = isset($requestData['TemplateDataCcInfo']) ? trim($requestData['TemplateDataCcInfo']) : '';
-            if (!empty($templateDataCcInfo)) {
-                $invoiceTemplateData->addCcInfo($templateDataCcInfo);
-            }
-
-            if (isset($requestData['templateDiscount']) && count(array_filter($requestData['templateDiscount'])) > 0) {
-                $templateDiscountCost = new Cost();
-                $this->setArrayToMethods(array_filter($requestData['templateDiscount']), $templateDiscountCost);
-                $invoiceTemplateData->setDiscount($templateDiscountCost);
-            }
-
-            if (isset($requestData['paymentTerm']) && count(array_filter($requestData['paymentTerm'])) > 0) {
-                $PaymentTerm = new PaymentTerm();
-                $this->setArrayToMethods(array_filter($requestData['paymentTerm']), $PaymentTerm);
-                $invoiceTemplateData->setPaymentTerm($PaymentTerm);
-            }
-
-            if (isset($requestData['attachments']) && count(array_filter($requestData['attachments'])) > 0) {
-                $attachment = new FileAttachment();
-                $this->setArrayToMethods(array_filter($requestData['attachments']), $attachment);
-                $invoiceTemplateData->setAttachments(array($attachment));
-            }
-
-            // ### Template Settings
-            $displayPreferences = new TemplateSettingsMetadata();
-            if (isset($requestData['TemplateSettingsMetadata']) && count(array_filter($requestData['TemplateSettingsMetadata'])) > 0) {
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettingsMetadata']), $displayPreferences);
-            }
-
-            $settingDate = new TemplateSettings();
-            if (isset($requestData['TemplateSettings']) && count(array_filter($requestData['TemplateSettings'])) > 0) {
-                $this->setArrayToMethods(array_filter($requestData['TemplateSettings']), $settingDate);
-            }
-
-            if (count(array_filter((array)$displayPreferences)) > 0) {
-                $settingDate->setDisplayPreference($displayPreferences);
-            }
-            // ### Template
-            $invoiceTemplate = new Template();
-            $invoiceTemplate->setTemplateId($templateId);
-            if (isset($requestData['Template']) && count(array_filter($requestData['Template'])) > 0) {
-                $this->setArrayToMethods(array_filter($requestData['Template']), $invoiceTemplate);
-            }
-
-            if (count(array_filter((array)$invoiceTemplateData)) > 0) {
-                $invoiceTemplate->setTemplateData($invoiceTemplateData);
-            }
-
-            if (count(array_filter((array)$settingDate)) > 0) {
-                $invoiceTemplate->addSetting($settingDate);
-            }
-
-            $requestArray = clone $invoiceTemplate;
-            $invoiceTemplate->update($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['INVOICE_TEMPLATE'] = $invoiceTemplate->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray->toJSON();
-            $returnArray['RAWRESPONSE'] = $invoiceTemplate->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/angelleye/PayPal/rest/notifications/NotificationsAPI.php b/src/angelleye/PayPal/rest/notifications/NotificationsAPI.php
deleted file mode 100644
index b3811e47..00000000
--- a/src/angelleye/PayPal/rest/notifications/NotificationsAPI.php
+++ /dev/null
@@ -1,394 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use \angelleye\PayPal\RestClass;
-use PayPal\Api\Webhook;
-use PayPal\Api\WebhookEventType;
-use PayPal\Api\WebhookEvent;
-use PayPal\Api\Notification;
-use PayPal\Api\CancelNotification;
-use PayPal\Api\VerifyWebhookSignature;
-
-/**
- * NotificationsAPI.
- * This class is responsible for Notifications APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class NotificationsAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }    
-    
-    /**
-     * Subscribes your webhook listener to events.
-     *
-     * @param array $requestData
-     * @return Array|Object
-     */
-    public function CreateWebhook($requestData){
-        
-        $webhook = new Webhook();
-        if(isset($requestData['Url'])){
-            $webhook->setUrl($requestData['Url']);
-        }
-
-        if(isset($requestData['EventTypes'])){
-            $webhookEventTypes = array();
-            foreach ($requestData['EventTypes'] as $value) {
-                $type = new WebhookEventType();
-                $type->setName($value);
-                $webhookEventTypes[] = $type;
-            }
-            $webhook->setEventTypes($webhookEventTypes);
-        }
-        
-        $request = clone $webhook;
-        
-        try {
-            $output = $webhook->create($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBHOOK']=$output->toArray();
-            $returnArray['RAWREQUEST']=$request->toJSON();
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        }
-        catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        }
-        catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Lists all webhooks for an app.
-     *
-     * @param array $requestData
-     * @return Array|Object
-     */
-    public function ListWebhooks($requestData){
-        try {
-            $output = \PayPal\Api\Webhook::getAllWithParams($requestData,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBHOOKS']=$output->toArray();
-            $returnArray['RAWREQUEST']= json_encode($requestData);
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }                
-    }    
-    
-    /**
-     * Shows details for a webhook, by ID.
-     *
-     * @param string $webhook_id
-     * @return Array|Object
-     */
-    public function GetWebhook($webhook_id){
-        try {
-            $output = \PayPal\Api\Webhook::get($webhook_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBHOOK']=$output->toArray();
-            $returnArray['RAWREQUEST']= '{webhook_id : '.$webhook_id.'}';
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Deletes a webhook, by ID.
-     *
-     * @param string $webhook_id
-     * @return Array|Object
-     */
-    public function DeleteWebhook($webhook_id){
-        $webhook = new Webhook();
-        $webhook->setId($webhook_id);
-        try {
-            $output = $webhook->delete($this->_api_context);           
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBHOOK_DELETE']=$output;
-            $returnArray['RAWREQUEST']= '{webhook_id : '.$webhook_id.'}';
-            $returnArray['RAWRESPONSE']=$output;
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Replaces webhook fields with new values. 
-     *
-     * @param string $webhook_id
-     * @param Array $requestData
-     * @return Array|Object
-     */
-    public function UpdateWebhook($webhook_id,$requestData){
-            $webhook = new Webhook();        
-            $pathRequest = new \PayPal\Api\PatchRequest();
-        try {
-            $webhook->setId($webhook_id);
-            $i=0;
-            foreach ($requestData as $value) {                                  
-                if(!empty($value['Op']) && !empty($value['Path']) && !empty($value['Value'])){
-                    $pathOperation = new \PayPal\Api\Patch();
-                    $pathOperation->setOp($value['Op'])
-                                        ->setPath($value['Path']);
-                    if($value['Path'] == '/event_types'){
-                        $webhookEventTypes = array();
-                        foreach($value['Value'] as $event){                                                        
-                                $type = new WebhookEventType();
-                                $type->setName($event);
-                                $webhookEventTypes[] = $type->toArray();                            
-                        }                        
-                        $pathOperation->setValue($webhookEventTypes);
-                    }
-                    else{                                                
-                            $pathOperation->setValue($value['Value']);                        
-                    }
-                    $pathRequest->addPatch($pathOperation);
-                    $i++;
-                }                   
-            } 
-           
-            if($i>0) {               
-                $output = $webhook->update($pathRequest,$this->_api_context);
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['WEBHOOK']=$output->toArray();         
-                $returnArray['RAWREQUEST']= $pathRequest->toJSON();
-                $returnArray['RAWRESPONSE']=$output->toJSON();
-                return $returnArray;                
-            }
-            else{
-                return "Fill Atleast One Array Field/Element";
-            }
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Lists webhook event notifications. Use query parameters to filter the response.
-     *
-     * @param Array $params
-     * @return Array|Object
-     */
-    public function SearchWebhookEvents($params){
-        $params = array_filter($params);
-        try {
-            $output = \PayPal\Api\WebhookEvent::all($params, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['EVENTS']=$output->toArray();         
-            $returnArray['RAWREQUEST']= $params;
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Retrieves the Webhooks event resource identified by event_id.
-     *
-     * @param string $event_id
-     * @return Array|Object
-     */
-    public function EventNotificationDetails($event_id){
-        try {
-            $output = \PayPal\Api\WebhookEvent::get($event_id, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['EVENT']=$output->toArray();         
-            $returnArray['RAWREQUEST']= '{event_id : '.$event_id.'}';
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Resends a webhook event notification, by ID. Any pending notifications are not resent.
-     * 
-     * @param string $event_id
-     * @return Array|Object
-     */
-    public function ResendEventNotification($event_id){
-        $WebhookEvent = new WebhookEvent();
-        $WebhookEvent->setId($event_id);
-        try {
-            $output = $WebhookEvent->resend($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['EVENT']=$output->toArray();         
-            $returnArray['RAWREQUEST']= '{event_id : '.$event_id.'}';
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * List events to which webhooks can subscribe.
-     *
-     * @return Array|Object
-     */
-    public function WebhooksEventTypes(){
-        $object = new \angelleye\PayPal\EventTypesClass();        
-        try {
-            $output = $object->get_all($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['EVENT_TYPES']=$output->toArray();         
-            $returnArray['RAWREQUEST']= '';
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Lists event subscriptions for a webhook, by ID.
-     *
-     * @param string $webhook_id
-     * @return Array|Object
-     */
-    public function WebhooksEventTypesById($webhook_id){
-        $object = new \angelleye\PayPal\EventTypesClass();        
-        try {
-            $output = $object->get_by_id($webhook_id,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['EVENT']=$output->toArray();         
-            $returnArray['RAWREQUEST']= '';
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Verifies a webhook signature.
-     *
-     * @param array $params
-     * @return Array|Object
-     */
-    public function VerifyWebhookSignature($headers,$webhook_id,$request_body){
-
-        try {
-            $signatureVerification = new VerifyWebhookSignature();
-            $signatureVerification->setAuthAlgo($headers['PAYPAL-AUTH-ALGO']);
-            $signatureVerification->setTransmissionId($headers['PAYPAL-TRANSMISSION-ID']);
-            $signatureVerification->setCertUrl($headers['PAYPAL-CERT-URL']);            
-            $signatureVerification->setWebhookId($webhook_id);
-            $signatureVerification->setTransmissionSig($headers['PAYPAL-TRANSMISSION-SIG']);
-            $signatureVerification->setTransmissionTime($headers['PAYPAL-TRANSMISSION-TIME']);
-            $signatureVerification->setRequestBody($request_body);
-            $output = $signatureVerification->post($this->_api_context);
-            $status = $output->getVerificationStatus();
-
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['STATUS']= $status;
-            $returnArray['RAWREQUEST']= '';
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        }
-        catch (Exception $ex){
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Simulates a webhook event.
-     *
-     * @param array $params
-     * @return Array|Object
-     */
-    public function SimulateEvent($params){
-        $object = new \angelleye\PayPal\EventTypesClass();
-        try {
-            $params = array_filter($params);
-            $output = $object->simulate_webhook_event_api($params,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['EVENT']=$output->toArray();
-            $returnArray['RAWREQUEST']= json_encode($params);
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (Exception $ex) {
-            return $this->createErrorResponse($ex);
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-}
diff --git a/src/angelleye/PayPal/rest/paymentexperience/PaymentExperianceAPI.php b/src/angelleye/PayPal/rest/paymentexperience/PaymentExperianceAPI.php
deleted file mode 100755
index 6324541f..00000000
--- a/src/angelleye/PayPal/rest/paymentexperience/PaymentExperianceAPI.php
+++ /dev/null
@@ -1,248 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use \PayPal\Api\FlowConfig;
-use \PayPal\Api\InputFields;
-use \PayPal\Api\Patch;
-use \PayPal\Api\Presentation;
-use \PayPal\Api\WebProfile;
-use \angelleye\PayPal\RestClass;
-
-/**
- * PaymentExperianceAPI.
- * This class is responsible for Payment Experiance APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class PaymentExperianceAPI extends RestClass {   
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-    
-    /**
-     * Creates a web experience profile. In the JSON request body, specify the profile name and details.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function CreateWebProfile($requestData){
-
-        try {
-            
-            // #### Payment Web experience profile resource
-            $webProfile = new WebProfile();
-
-            if(isset($requestData['FlowConfig'])){
-                $flowConfig = new FlowConfig();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['FlowConfig']), $flowConfig);
-                $webProfile->setFlowConfig($flowConfig);
-            }
-
-            if(isset($requestData['presentation'])){
-                $presentation = new Presentation();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['presentation']), $presentation);
-                $webProfile->setPresentation($presentation);
-            }
-
-            if(isset($requestData['InputFields'])){
-                $inputFields = new InputFields();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['InputFields']), $inputFields);
-                $webProfile->setInputFields($inputFields);
-            }
-            if(isset($requestData['WebProfile'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['WebProfile']), $webProfile);
-            }
-            $requestArray = clone $webProfile;
-            $createProfileResponse = $webProfile->create($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBPROFILE'] = $createProfileResponse->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$createProfileResponse->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Shows details for a web experience profile, by ID.
-     *
-     * @param string $profileId
-     * @return array|object
-     */
-    public function GetWebProfile($profileId){
-        try {
-            $webProfile = WebProfile::get($profileId,$this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBPROFILE'] = $webProfile->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$profileId.'}';
-            $returnArray['RAWRESPONSE']=$webProfile->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Lists the latest 20 web experience profiles for a merchant or subject. To show details for these or additional profiles, you can show web experience profile details by ID.
-     *
-     * @return array|object
-     */
-    public function ListWebProfiles(){
-        try {
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['LIST'] = WebProfile::get_list($this->_api_context);
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Deletes a web experience profile, by ID.
-     *
-     * @param string $profileId
-     * @return array|object
-     */
-    public function DeleteWebProfile($profileId){
-        try {
-            $webProfile = new WebProfile();
-            $webProfile->setId($profileId);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DELETE_RESPONSE'] = $webProfile->delete($this->_api_context);
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Partially-updates a web experience profile, by ID.
-     *
-     * @param array $patchArray
-     * @param string $profileID
-     * @return array|object
-     */
-    public function PartiallyUpdateWebProfile($patchArray,$profileID){
-
-        $webProfile = new WebProfile();
-        $webProfile->setId($profileID);
-        
-        $patches=array();
-        
-        foreach ($patchArray as $patch){
-           if($patch['Op']=='remove'){
-              unset($patch['Value']);
-           }
-            $patchOperation = new Patch();
-            $this->setArrayToMethods($patch, $patchOperation);
-            array_push($patches, $patchOperation);
-        }              
-        try {
-            // Execute the partial update, to carry out these two operations on a given web profile object
-            if ($webProfile->partial_update($patches, $this->_api_context)) {                
-                $webProfile = WebProfile::get($webProfile->getId(), $this->_api_context);                
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['WEBPROFILE'] = $webProfile->toArray();
-                $returnArray['RAWREQUEST']=$patches;
-                $returnArray['RAWRESPONSE']=$webProfile->toJSON();
-                return $returnArray;                
-            }
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Updates a web experience profile, by ID.
-     *
-     * @param array $requestData
-     * @param string $profileID
-     * @return array|object
-     */
-    public function UpdateWebProfile($requestData,$profileID){
-        
-        try {            
-            // #### Payment Web experience profile resource
-            $webProfile = WebProfile::get($profileID, $this->_api_context);
-            
-            if(isset($requestData['FlowConfig'])){
-                $flowConfig = $webProfile->getFlowConfig();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['FlowConfig']), $flowConfig);
-                $webProfile->setFlowConfig($flowConfig);
-            }
-
-            if(isset($requestData['presentation'])){
-                $presentation = $webProfile->getPresentation();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['presentation']), $presentation);
-                $webProfile->setPresentation($presentation);
-            }
-
-            if(isset($requestData['InputFields'])){
-                $inputFields = $webProfile->getInputFields();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['InputFields']), $inputFields);
-                $webProfile->setInputFields($inputFields);
-            }
-            
-            if(isset($requestData['WebProfile'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['WebProfile']), $webProfile);
-            }
-            $requestArray = clone $webProfile;
-            $webProfile->update($this->_api_context);
-            $updatedWebProfile = WebProfile::get($profileID, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['WEBPROFILE'] = $updatedWebProfile->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$updatedWebProfile->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-}
diff --git a/src/angelleye/PayPal/rest/payments/PaymentAPI.php b/src/angelleye/PayPal/rest/payments/PaymentAPI.php
deleted file mode 100755
index a535e504..00000000
--- a/src/angelleye/PayPal/rest/payments/PaymentAPI.php
+++ /dev/null
@@ -1,1296 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use PayPal\Api\Amount;
-use PayPal\Api\Address;
-use PayPal\Api\Authorization;
-use PayPal\Api\Capture;
-use PayPal\Api\CreditCard;
-use PayPal\Api\CreditCardToken;
-use PayPal\Api\Details;
-use PayPal\Api\ExecutePayment;
-use PayPal\Api\FundingInstrument;
-use PayPal\Api\FuturePayment;
-use PayPal\Api\Item;
-use PayPal\Api\ItemList;
-use PayPal\Api\Order;
-use PayPal\Api\Payer;
-use PayPal\Api\Payee;
-use PayPal\Api\Payment;
-use PayPal\Api\PaymentCard;
-use PayPal\Api\PaymentExecution;
-use PayPal\Api\RedirectUrls;
-use PayPal\Api\Refund;
-use PayPal\Api\RefundRequest;
-use PayPal\Api\Sale;
-use PayPal\Api\Transaction;
-use \angelleye\PayPal\RestClass;
-use angelleye\PayPal\PayPal;
-
-
-/**
- * PaymentAPI.
- * This class is responsible for Payment APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class PaymentAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     * Creates a sale, an authorized payment to be captured later, or an order. 
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function CreatePayment($requestData) {
-        try {
-            // ### PaymentCard
-            // A resource representing a payment card that can be used to fund a payment.
-            $card = new PaymentCard();
-            if(isset($requestData['paymentCard'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['paymentCard']), $card);
-            }
-
-            if(isset($requestData['billingAddress'])){
-                $ba = $this->checkEmptyObject($requestData['billingAddress']);
-                if(!empty($ba)){
-                    $this->setArrayToMethods(array("BillingAddress" => $ba), $card);
-                }
-            }
-            
-            // ### FundingInstrument
-            // A resource representing a Payer's funding instrument.
-            $fi = new FundingInstrument();
-            $fi->setPaymentCard($card);
-                       
-            // ### Payer
-            // A resource representing a Payer that funds a payment
-            $payer = new Payer();
-            $payer->setPaymentMethod("credit_card");
-            $payer->setFundingInstruments(array($fi));
-             
-            // ### Itemized information
-            // (Optional) Lets you specify item wise information
-            $itemListArray = array();
-            if(isset($requestData['orderItems'])){
-                foreach ($this->checkEmptyObject($requestData['orderItems']) as $value) {
-                   $item = new Item();
-                   $array = array_filter($value);
-                   if (count($array) > 0) {
-                       $this->setArrayToMethods($array, $item);
-                       array_push($itemListArray, $item);
-                   }
-               }   
-            }
-            
-            $itemList = new ItemList();
-            $itemListArray = $this->checkEmptyObject($itemListArray);
-            if(!empty($itemListArray)){
-                $itemList->setItems($itemListArray);
-            }            
-            
-            // ### Additional payment details
-            // Use this optional field to set additional payment information such as tax, shipping charges etc.
-            $details = new Details();
-            if (isset($requestData['paymentDetails'])) {                
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['paymentDetails']), $details);
-            }            
-            // ### Amount
-            // Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
-            $amount = new Amount();
-            if (isset($requestData['amount'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['amount']), $amount);
-            }
-
-            $detailsArray = $this->checkEmptyObject((array)$details);
-            if (!empty($detailsArray)) {
-                $amount->setDetails($details);
-            }
-
-            // ### Transaction
-            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
-            $transaction = new Transaction();
-            $amountArray = $this->checkEmptyObject((array)$amount);
-            if(!empty($amountArray)){
-                $transaction->setAmount($amount);
-            }
-
-            $itemListArray = $this->checkEmptyObject((array)$itemList);
-            if (!empty($itemListArray)) {
-                $transaction->setItemList($itemList);
-            }
-            
-            if (isset($requestData['transaction'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['transaction']), $transaction);
-            }
-
-            // ### Payment
-            // A Payment Resource; create one using the above types and intent set to sale 'sale'
-            $payment = new Payment();
-            if(isset($requestData['ExperienceProfileId']) && !empty($requestData['ExperienceProfileId'])){
-                $payment->setExperienceProfileId($requestData['ExperienceProfileId']);
-            }
-            if(isset($requestData['NoteToPayer']) && !empty($requestData['NoteToPayer'])){
-                $payment->setNoteToPayer($requestData['NoteToPayer']);
-            }
-            
-            $payment->setIntent(trim($requestData['intent']));
-            $payerArray = $this->checkEmptyObject((array)$payer);
-            if(!empty($payerArray)){
-                $payment->setPayer($payer);
-            }
-
-            $transactionArray = $this->checkEmptyObject((array)$transaction);
-            if(!empty($transactionArray)){
-                $payment->setTransactions(array($transaction));
-            }            
-            // ### Create Payment
-            // Create a payment by calling the payment->create() method with a valid ApiContext. The return object contains the state.
-            $requestArray = clone $payment;
-            $payment->create($this->_api_context);
-            if ($requestData['intent'] == 'authorize') {
-                $transactions = $payment->getTransactions();
-                $relatedResources = $transactions[0]->getRelatedResources();
-                $authorization = $relatedResources[0]->getAuthorization();
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['AUTHORIZATION'] = $authorization->toArray();
-                $returnArray['PAYMENT'] = $payment->toArray();
-                $returnArray['RAWREQUEST']=$requestArray->toJSON();
-                $returnArray['RAWRESPONSE']=$payment->toJSON();
-            } else {
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['PAYMENT']=$payment->toArray();
-                $returnArray['RAWREQUEST']=$requestArray->toJSON();
-                $returnArray['RAWRESPONSE']=$payment->toJSON();
-            }
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($payment->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     *  Creates a sale, an authorized payment to be captured later, or an order. 
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function CreatePaymentUsingPayPal($requestData) {
-
-        try {
-            // ### Payer
-            // A resource representing a Payer that funds a payment
-            // For paypal account payments, set payment method
-            // to 'paypal'.
-            $payer = new Payer();
-            $payer->setPaymentMethod("paypal");
-
-            // ### Itemized information
-            // (Optional) Lets you specify item wise information
-            $itemListArray = array();
-            if (isset($requestData['orderItems'])) {                                        
-                foreach ($this->checkEmptyObject($requestData['orderItems']) as $value) {
-                    $item = new Item();
-                    $array = array_filter($value);
-                    if (count($array) > 0) {
-                        $this->setArrayToMethods($array, $item);
-                        array_push($itemListArray, $item);
-                    }
-                }
-            }
-            $itemList = new ItemList();
-            if(!empty($itemListArray)){
-                $itemList->setItems($itemListArray);
-            }
-            
-            // ### Additional payment details
-            // Use this optional field to set additional payment information such as tax, shipping charges etc.
-            $details = new Details();
-            if (isset($requestData['paymentDetails'])) {                
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['paymentDetails']), $details);
-            }
-
-            // ### Amount
-            // Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
-            $amount = new Amount();
-            if (isset($requestData['amount'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['amount']), $amount);
-            }
-            
-            $detailArray = $this->checkEmptyObject((array)$details); 
-            if ( !empty($detailArray) ) {
-                $amount->setDetails($details);
-            }
-
-            // ### Transaction
-            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
-            $transaction = new Transaction();
-            $amountArray = $this->checkEmptyObject((array)$amount);
-            if (!empty($amountArray)) {
-                $transaction->setAmount($amount);
-            }
-            $itemListArr=$this->checkEmptyObject((array)$itemList);
-            if (!empty($itemListArr)) {
-                $transaction->setItemList($itemList);
-            }
-            if (isset($requestData['transaction'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['transaction']), $transaction);
-            }
-            if(isset($requestData['invoiceNumber']) && !empty($requestData['invoiceNumber'])){
-                $transaction->setInvoiceNumber($requestData['invoiceNumber']);
-            }
-
-            // ### Redirect urls
-            // Set the urls that the buyer must be redirected to after 
-            // payment approval/ cancellation.
-            $baseUrl = isset($requestData['urls']['BaseUrl']) ? $requestData['urls']['BaseUrl'] : '';
-            
-            $redirectUrls = new RedirectUrls();
-            if(isset($requestData['urls']['ReturnUrl'])){
-                $redirectUrls->setReturnUrl($baseUrl . $requestData['urls']['ReturnUrl']);
-            }
-            if(isset($requestData['urls']['CancelUrl'])){
-                $redirectUrls->setCancelUrl($baseUrl . $requestData['urls']['CancelUrl']);
-            }
-            
-            // ### Payment
-            // A Payment Resource; create one using the above types and intent set to sale 'sale'
-            $payment = new Payment();
-            
-            if(isset($requestData['intent']) && !empty($requestData['intent'])){
-                $payment->setIntent($requestData['intent']);
-            }
-
-            $payerArray = $this->checkEmptyObject((array)$payer);
-            if(!empty($payerArray)){
-                $payment->setPayer($payer);
-            }
-
-            $redirectUrlsArray = $this->checkEmptyObject((array)$redirectUrls);
-            if(!empty($redirectUrlsArray)){
-                $payment->setRedirectUrls($redirectUrls);
-            }
-
-            $transactionArray = $this->checkEmptyObject((array)$transaction);
-            if(!empty($transactionArray)){
-                $payment->setTransactions(array($transaction));
-            }
-
-            if(isset($requestData['ExperienceProfileId']) && !empty($requestData['ExperienceProfileId'])){
-                $payment->setExperienceProfileId(trim($requestData['ExperienceProfileId']));
-            }
-
-            if(isset($requestData['NoteToPayer']) && !empty($requestData['NoteToPayer'])){
-                $payment->setNoteToPayer(trim($requestData['NoteToPayer']));
-            }
-            
-            // ### Create Payment
-            // Create a payment by calling the payment->create() method with a valid ApiContext. The return object contains the state.
-            $requestArray = clone $payment;
-            $payment->create($this->_api_context);
-
-            // ### Get redirect url
-            // The API response provides the url that you must redirect
-            // the buyer to. Retrieve the url from the $payment->getApprovalLink()
-            // method
-            $approvalUrl = $payment->getApprovalLink();            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYMENT'] = array('approvalUrl' => $approvalUrl, 'payment' => $payment->toArray());
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$payment->toJSON();            
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Creates a sale, an authorized payment to be captured later, or an order with third party payment.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function CreateThirdPartyPayment($requestData){
-        
-        try {
-            // ### Payer
-            // A resource representing a Payer that funds a payment
-            // For paypal account payments, set payment method
-            // to 'paypal'.
-            $payer = new Payer();
-            $payer->setPaymentMethod("paypal");
-
-            // ### Itemized information
-            // (Optional) Lets you specify item wise information
-            $itemListArray = array();
-            if (isset($requestData['orderItems'])) {                                        
-                foreach ($this->checkEmptyObject($requestData['orderItems']) as $value) {
-                    $item = new Item();
-                    $array = array_filter($value);
-                    if (count($array) > 0) {
-                        $this->setArrayToMethods($array, $item);
-                        array_push($itemListArray, $item);
-                    }
-                }
-            }
-            $itemList = new ItemList();
-            if(!empty($itemListArray)){
-                $itemList->setItems($itemListArray);
-            }
-            
-            // ### Additional payment details
-            // Use this optional field to set additional payment information such as tax, shipping charges etc.
-            $details = new Details();
-            if (isset($requestData['paymentDetails'])) {                
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['paymentDetails']), $details);
-            }
-
-            // ### Amount
-            // Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
-            $amount = new Amount();
-            if (isset($requestData['amount'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['amount']), $amount);
-            }
-            
-            $detailArray = $this->checkEmptyObject((array)$details); 
-            if ( !empty($detailArray) ) {
-                $amount->setDetails($details);
-            }
-
-            // ### Transaction
-            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
-
-            $transaction = new Transaction();
-            $amountArray = $this->checkEmptyObject((array)$amount);
-            if (!empty($amountArray)) {
-                $transaction->setAmount($amount);
-            }
-            $itemListArr=$this->checkEmptyObject((array)$itemList);
-            if (!empty($itemListArr)) {
-                $transaction->setItemList($itemList);
-            }
-            if (isset($requestData['transaction'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['transaction']), $transaction);
-            }
-                        
-            if(isset($requestData['Payee']) && !empty($requestData['Payee'])){
-                // Specify a payee with that user's email or merchant id
-                // Merchant Id can be found at https://www.paypal.com/businessprofile/settings/                
-                $payee = new Payee();
-                $payee->setEmail($requestData['Payee']);
-                $transaction->setPayee($payee);
-            }
-            
-            
-            if(isset($requestData['invoiceNumber']) && !empty($requestData['invoiceNumber'])){
-                $transaction->setInvoiceNumber($requestData['invoiceNumber']);
-            }
-
-            // ### Redirect urls
-            // Set the urls that the buyer must be redirected to after 
-            // payment approval/ cancellation.
-            $baseUrl = isset($requestData['urls']['BaseUrl']) ? $requestData['urls']['BaseUrl'] : '';
-            
-            $redirectUrls = new RedirectUrls();
-            if(isset($requestData['urls']['ReturnUrl'])){
-                $redirectUrls->setReturnUrl($baseUrl . $requestData['urls']['ReturnUrl']);
-            }
-            if(isset($requestData['urls']['CancelUrl'])){
-                $redirectUrls->setCancelUrl($baseUrl . $requestData['urls']['CancelUrl']);
-            }
-            
-            // ### Payment
-            // A Payment Resource; create one using the above types and intent set to sale 'sale'
-            $payment = new Payment();
-            
-            if(isset($requestData['intent']) && !empty($requestData['intent'])){
-                $payment->setIntent($requestData['intent']);
-            }
-
-            if(isset($requestData['intent']) && !empty($requestData['intent'])){
-                $payment->setIntent($requestData['intent']);
-            }
-
-            $payerArray = $this->checkEmptyObject((array)$payer);
-            if(!empty($payerArray)){
-                $payment->setPayer($payer);
-            }
-            $redirectUrlsArray = $this->checkEmptyObject((array)$redirectUrls);
-            if(!empty($redirectUrlsArray)){
-                $payment->setRedirectUrls($redirectUrls);
-            }
-            $transactionArray = $this->checkEmptyObject((array)$transaction);
-            if(!empty($transactionArray)){
-                $payment->setTransactions(array($transaction));
-            }
-            if(isset($requestData['ExperienceProfileId']) && !empty($requestData['ExperienceProfileId'])){
-                $payment->setExperienceProfileId(trim($requestData['ExperienceProfileId']));
-            }
-            if(isset($requestData['NoteToPayer']) && !empty($requestData['NoteToPayer'])){
-                $payment->setNoteToPayer(trim($requestData['NoteToPayer']));
-            }
-            
-            // ### Create Payment
-            // Create a payment by calling the payment->create() method with a valid ApiContext. The return object contains the state.
-            $requestArray = clone $payment;
-            $payment->create($this->_api_context);
-
-            // ### Get redirect url
-            // The API response provides the url that you must redirect
-            // the buyer to. Retrieve the url from the $payment->getApprovalLink()
-            // method
-            $approvalUrl = $payment->getApprovalLink();            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYMENT'] = array('approvalUrl' => $approvalUrl, 'payment' => $payment->toArray());
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$payment->toJSON();    
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($payment->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Creates a sale, an authorized payment to be captured later, or an order with saved card details.
-     *
-     * @param array $requestData
-     * @param string $credit_card_id
-     * @return array|object
-     */
-    public function CreatePaymentUsingSavedCardVault($requestData, $credit_card_id) {
-
-        try {
-            ///$card = new CreditCard();
-            //$card->setId($credit_card_id);
-            // ### Credit card token
-            // Saved credit card id from CreateCreditCard.
-            $creditCardToken = new CreditCardToken();
-            $creditCardToken->setCreditCardId($credit_card_id);
-            // ### FundingInstrument
-            // A resource representing a Payer's funding instrument.
-            // For stored credit card payments, set the CreditCardToken
-            // field on this object.
-            $fi = new FundingInstrument();
-            $fi->setCreditCardToken($creditCardToken);
-
-            // ### Payer
-            // A resource representing a Payer that funds a payment
-            // For stored credit card payments, set payment method
-            // to 'credit_card'.
-            $payer = new Payer();
-            $payer->setPaymentMethod("credit_card");
-            $payer->setFundingInstruments(array($fi));
-
-            // ### Itemized information
-            // (Optional) Lets you specify item wise information
-            $itemListArray = array();
-            if(isset($requestData['orderItems'])){
-                foreach ($this->checkEmptyObject($requestData['orderItems']) as $value) {
-                    $item = new Item();
-                    $array = array_filter($value);
-                    if (count($array) > 0) {
-                        $this->setArrayToMethods($array, $item);
-                        array_push($itemListArray, $item);
-                    }
-                }
-            }
-            
-            $itemList = new ItemList();
-            if(!empty($itemListArray)){
-                $itemList->setItems($itemListArray);
-            }
-            // ### Additional payment details
-            // Use this optional field to set additional payment information such as tax, shipping charges etc.
-
-            if (isset($requestData['paymentDetails'])) {
-                $details = new Details();
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['paymentDetails']), $details);
-            }
-
-            // ### Amount
-            // Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
-            $amount = new Amount();
-            if (isset($requestData['amount'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['amount']), $amount);
-            }
-
-            $detailsArray = $this->checkEmptyObject((array)$details);
-            if (!empty($detailsArray)) {
-                $amount->setDetails($details);
-            }
-
-            // ### Transaction
-            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
-            $transaction = new Transaction();
-            $amountArray = $this->checkEmptyObject((array)$amount);
-            if(!empty($amountArray)){
-                $transaction->setAmount($amount);
-            }
-
-            $itemListArray = $this->checkEmptyObject((array)$itemList);
-            if (!empty($itemListArray)) {
-                $transaction->setItemList($itemList);
-            }
-
-            if (isset($requestData['transaction'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['transaction']), $transaction);
-            }
-
-            // ### Payment
-            // A Payment Resource; create one using the above types and intent set to sale 'sale'
-            $payment = new Payment();
-            $payment->setIntent($requestData['intent']);
-
-            $payerArray = $this->checkEmptyObject((array)$payer);
-            if(!empty($payerArray)){
-                $payment->setPayer($payer);
-            }
-            $transactionArray = $this->checkEmptyObject((array)$transaction);
-            if(!empty($transactionArray)){
-                $payment->setTransactions(array($transaction));
-            }
-            $requestArray = clone $payment;
-            $payment->create($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYMENT'] = $payment->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$payment->toJSON();
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($payment->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {            
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for an authorization, by ID.
-     *
-     * @param string $authorizationId
-     * @return array|object
-     */
-    public function GetAuthorization($authorizationId) {
-        try {
-            $result = Authorization::get($authorizationId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AUTHORIZATION'] = $result->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$authorizationId.'}';
-            $returnArray['RAWRESPONSE']=$result->toJSON();
-            return $returnArray;                        
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for a payment, by ID.
-     *
-     * @param string $PaymentID
-     * @return array|object
-     */
-    public function ShowPaymentDetails($PaymentID) {
-        try {
-            $payment = Payment::get($PaymentID, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYMENT'] = $payment->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$PaymentID.'}';
-            $returnArray['RAWRESPONSE']=$payment->toJSON();
-            return $returnArray;                                    
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Lists payments that are completed.
-     *
-     * @param array $params
-     * @return array|object
-     */
-    public function ListPayments($params) {
-        try {
-            $payments = Payment::all(array_filter($params), $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYMENTS'] = $payments->toArray();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Captures and processes an authorization, by ID. 
-     *
-     * @param string $authorizationId
-     * @param array $amountArray
-     * @return array|object
-     */
-    public function AuthorizationCapture($authorizationId, $amountArray) {
-        // # AuthorizationCapture
-
-        /** @var Authorization $authorization */
-        $authorization = new Authorization();
-
-        try {
-            $authId = $authorization->setId($authorizationId);
-            $amt = new Amount();
-            $this->setArrayToMethods($amountArray, $amt);
-            ### Capture
-            $capture = new Capture();
-            $capture->setAmount($amt);
-            // Perform a capture
-            $requestArray = clone $authorization;
-            $getCapture = $authorization->capture($capture, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CAPTURE'] = $getCapture->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$getCapture->toJSON();  
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($getCapture->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Voids, or cancels, an authorization, by ID. You cannot void a fully captured authorization.
-     *
-     * @param string $authorizationId
-     * @return array|object
-     */
-    public function VoidAuthorization($authorizationId) {
-        // # VoidAuthorization
-        try {
-            // Lookup the authorization
-            $authorization = Authorization::get($authorizationId, $this->_api_context);
-            // Void the authorization
-            $requestArray = clone  $authorization;
-            $voidedAuth = $authorization->void($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['AUTH_VOID'] = $voidedAuth->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$voidedAuth->toJSON();  
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Captures and processes an authorization, by ID. 
-     *
-     * @param string $authorizationCaptureId
-     * @return array|object
-     */
-    public function GetCapture($authorizationCaptureId) {
-        // # GetCapture       
-        try {
-            $capture = Capture::get($authorizationCaptureId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CAPTURE'] = $capture->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$authorizationCaptureId.'}';
-            $returnArray['RAWRESPONSE']=$capture->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Shows details for an order, by ID.
-     *
-     * @param string $orderId
-     * @return array|object
-     */
-    public function OrderGet($orderId){
-        // #Get Order Sample        
-        try {
-            $result = Order::get($orderId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['ORDER'] = $result->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$orderId.'}';
-            $returnArray['RAWRESPONSE']=$result->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Authorizes an order, by ID.
-     *
-     * @param string  $orderId
-     * @param array $amountArray
-     * @return array|object
-     */
-    public function OrderAuthorize($orderId,$amountArray){
-        try {
-            $order= new Order();
-            $order->setId($orderId);
-            $authorization = new Authorization();
-            $amount = new Amount();
-            $this->setArrayToMethods($amountArray, $amount);
-            $authorization->setAmount($amount);
-            $requestArray = clone $order;
-            $result = $order->authorize($authorization,$this->_api_context);
-            $authorizationId=$result->id;
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['ORDER_AUTH'] = $result->toArray();
-            $returnArray['AUTH_Id'] = $authorizationId;
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$result->toJSON();            
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Captures a payment for an order, by ID. 
-     *
-     * @param string $orderId
-     * @param array $amountArray
-     * @param boolen $is_final_capture
-     * @return array
-     */
-    public function OrderCapture($orderId,$amountArray=array(),$is_final_capture = false){
-        try {
-            $order= new Order();
-            $order->setId($orderId);
-
-            $capture = new Capture();
-            $capture->setIsFinalCapture($is_final_capture);
-
-            if(!empty($amountArray)){
-                $amount = new Amount();
-                $this->setArrayToMethods($amountArray, $amount);
-                $capture->setAmount($amount);
-            }
-
-            $requestArray = clone $order;
-            $result = $order->capture($capture, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['ORDER_CAPTURE'] = $result->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$result->toJSON();            
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($result->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Voids, or cancels, an order, by ID. 
-     *
-     * @param string $orderId
-     * @return array|object
-     */
-    public function OrderDoVoid($orderId){
-        try {            
-            
-            $order= new Order();
-            $order->setId($orderId);
-            $requestArray = clone $order;
-            $result = $order->void($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['ORDER_VOID'] = $result->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$result->toJSON();            
-            return $returnArray;                       
-            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Refunds a captured payment, by ID.
-     *
-     * @param string $capture_id
-     * @param array $amountArray
-     * @param array $refundParameters
-     * @return array|object
-     */
-    public function RefundCapture($capture_id,$amountArray,$refundParameters){
-        try {            
-            
-            $capture = new Capture();
-            $capture->setId($capture_id);
-            
-            $amount = new Amount();
-            $this->setArrayToMethods($amountArray, $amount);
-            // ### Refund
-            // Create a refund object indicating
-            // refund amount and call the refund method
-            
-            $refundRequest = new RefundRequest();
-            $refundRequest->setAmount($amount);
-            $this->setArrayToMethods(array_filter($refundParameters), $refundRequest);                        
-            $requestArray = clone $capture;
-            $captureRefund = $capture->refundCapturedPayment($refundRequest,$this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REFUND_CAPTURE'] = $captureRefund->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$captureRefund->toJSON();            
-            return $returnArray;                                  
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * 
-     * @param string $refund_id
-     * @return array|object
-     */
-    public function ShowRefundDetails($refund_id){
-        try {
-            $refund = Refund::get($refund_id, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REFUND'] = $refund->toArray();
-            $returnArray['RAWREQUEST']='{refund_id :'.$refund_id.'}';
-            $returnArray['RAWRESPONSE']=$refund->toJSON();
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($refund->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Reauthorizes a PayPal account payment, by authorization ID. To ensure that funds are still available, reauthorize a payment after the initial three-day honor period. Supports only the `amount` request parameter.
-     * @param string $authorizationId
-     * @param array $amount
-     * @return array|object
-     */
-    public function Reauthorization($authorizationId,$amount){
-        try {
-            $authorization = Authorization::get($authorizationId, $this->_api_context);
-            
-            $amt = new Amount();
-            $amt->setCurrency($amount['Currency'])
-                ->setTotal($amount['Total']);
-            if(isset($amount['Details'])){
-                $details = new Details();
-                $detailArray = $this->checkEmptyObject($amount['Details']);
-                if(!empty($detailArray)){
-                    $this->setArrayToMethods($detailArray, $details);
-                    $amt->setDetails($details);
-                }
-
-
-            }
-            
-            // ### Reauthorize with amount being reauthorized
-            $authorization->setAmount($amt);
-            $reAuthorization = $authorization->reauthorize($this->_api_context);
-            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['REAUTHORIZATION'] = $reAuthorization->toArray();
-            $returnArray['RAWREQUEST']=$authorization->toJSON();
-            $returnArray['RAWRESPONSE']=$reAuthorization->toJSON();
-            return $returnArray;
-            
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Shows details for a sale, by ID. Returns only sales that were created through the REST API.
-     * @param string $sale_id
-     * @return array|object
-     */
-    public function GetSale($sale_id){
-        // # GetSale       
-        try {
-            $sale = Sale::get($sale_id, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['SALE'] = $sale->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$sale_id.'}';
-            $returnArray['RAWRESPONSE']=$sale->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * 
-     * @param string $sale_id
-     * @param array $amount
-     * @param array $refundParameters
-     * @return array|object
-     */
-    public function RefundSale($sale_id,$amount,$refundParameters){
-        // Refund Sale       
-        try {
-            
-            // ### Refund amount
-            // Includes both the refunded amount (to Payer) 
-            // and refunded fee (to Payee).
-            
-            $amt = new Amount();            
-            $amt->setCurrency($amount['Currency'])
-                ->setTotal($amount['Total']);
-            if(isset($amount['Details'])){
-                $details = new Details();
-                $detailArray = $this->checkEmptyObject($amount['Details']);
-                if(!empty($detailArray)){
-                    $this->setArrayToMethods($detailArray, $details);
-                    $amt->setDetails($details);
-                }
-            }
-            
-            // ### Refund object
-            $refundRequest = new RefundRequest();
-            $refundRequest->setAmount($amt);
-            
-            $requestArray = $this->checkEmptyObject($refundParameters);
-            if(!empty($requestArray)){
-                $this->setArrayToMethods($requestArray, $refundRequest);                
-            }
-                
-            $sale = new Sale();
-            $sale->setId($sale_id);
-            
-            $refundedSale = $sale->refundSale($refundRequest, $this->_api_context);
-
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['SALE'] = $refundedSale->toArray();
-            $returnArray['RAWREQUEST']=$refundRequest->toJSON();
-            $returnArray['RAWRESPONSE']=$sale->toJSON();
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($refundedSale->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-       
-    /**
-     * Partially updates a payment, by ID. 
-     * You can update the amount, shipping address, invoice ID, and custom data.
-     * You cannot update a payment after the payment executes.
-     * @param string $paymentId
-     * @param array $patchArray
-     * @return array|object
-     */
-    public function UpdatePayment($paymentId,$patchArray){
-        try {            
-            $patchRequest = new \PayPal\Api\PatchRequest();
-            $payment = new Payment();
-            $payment->setId($paymentId);            
-                   
-            $array1 = array();
-            foreach ($patchArray as $value){
-                $pathOperation = new \PayPal\Api\Patch();
-                $ob=json_decode(json_encode($value['value']));
-                $pathOperation->setOp($value['operation'])
-                                 ->setPath($value['path'])
-                                 ->setValue($ob);                
-                $array1[] = $pathOperation;
-            }            
-            $patchRequest->setPatches($array1);                         
-            $output = $payment->update($patchRequest, $this->_api_context);     
-            if($output == true){
-                $result = Payment::get($payment->getId(), $this->_api_context);
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['PAYMENT'] = $result->toArray();
-                $returnArray['RAWREQUEST']=$patchRequest->toJSON();
-                $returnArray['RAWRESPONSE']=$output;
-            }
-            else{
-                $returnArray['RESULT'] = 'Failed';
-                $returnArray['RETURN'] = $output;
-            }
-            return $returnArray;                                  
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Executes, or completes, a PayPal payment that the payer has approved. You can optionally update selective payment information when you execute a payment.
-     * @param string $paymentId
-     * @param string $payer_id
-     * @param array $amount
-     * @return Array
-     */
-    public function ExecutePayment($paymentId,$payer_id,$amount=array()){
-
-        $payment = Payment::get($paymentId, $this->_api_context);
-
-        $intent = $payment->getIntent();
-
-        // ### Payment Execute
-        // PaymentExecution object includes information necessary
-        // to execute a PayPal account payment.
-        // The payer_id is added to the request query parameters
-        // when the user is redirected from paypal back to your site
-
-        $execution = new PaymentExecution();
-        $execution->setPayerId($payer_id);
-
-        if (isset($amount['Currency']) && !empty($amount['Currency']) && isset($amount['Total']) && !empty($amount['Total'])){
-
-            $transaction = new Transaction();
-
-            $amt = new Amount();
-            $amt->setCurrency($amount['Currency'])
-                ->setTotal($amount['Total']);
-
-            $details = new Details();
-            $detailArray = $this->checkEmptyObject($amount['Details']);
-            if(!empty($detailArray)){
-                $this->setArrayToMethods($detailArray, $details);
-                $amt->setDetails($details);
-            }
-            $transaction->setAmount($amt);
-            // Add the above transaction object inside our Execution object.
-            $execution->addTransaction($transaction);
-        }
-
-        try {
-            // Execute the payment
-            $result = $payment->execute($execution, $this->_api_context);
-
-            $returnArray['RESULT'] = 'Success';
-            if ($intent == 'authorize') {
-                $transactions = $result->getTransactions();
-                $relatedResources = $transactions[0]->getRelatedResources();
-                $authorization = $relatedResources[0]->getAuthorization();
-                $returnArray['AUTHORIZATION'] = $authorization->toArray();
-            }
-            if($intent == 'order'){
-                $transactions = $payment->getTransactions();
-                $transaction = $transactions[0];
-                $relatedResources = $transaction->getRelatedResources();
-                $relatedResource = $relatedResources[0];
-                $order = $relatedResource->getOrder();
-                $returnArray['ORDER'] = $order->toArray();
-            }
-            $returnArray['PAYMENT'] = $result->toArray();
-            $returnArray['RAWREQUEST']=$execution->toJSON();
-            $returnArray['RAWRESPONSE']=$result->toJSON();
-            
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($result->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-
-    }
-
-
-    public function CreateFuturePayment($method,$requestData){
-        try {
-            // ### Payer
-            // A resource representing a Payer that funds a payment
-            // For paypal account payments, set payment method
-            // to 'paypal'.
-            $payer = new Payer();
-            $payer->setPaymentMethod($method);
-
-            // ### Itemized information
-            // (Optional) Lets you specify item wise information
-            $itemListArray = array();
-            if (isset($requestData['orderItems'])) {
-                foreach ($this->checkEmptyObject($requestData['orderItems']) as $value) {
-                    $item = new Item();
-                    $array = array_filter($value);
-                    if (count($array) > 0) {
-                        $this->setArrayToMethods($array, $item);
-                        array_push($itemListArray, $item);
-                    }
-                }
-            }
-            $itemList = new ItemList();
-            if(!empty($itemListArray)){
-                $itemList->setItems($itemListArray);
-            }
-
-            // ### Additional payment details
-            // Use this optional field to set additional payment information such as tax, shipping charges etc.
-            $details = new Details();
-            if (isset($requestData['paymentDetails'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['paymentDetails']), $details);
-            }
-
-            // ### Amount
-            // Lets you specify a payment amount. You can also specify additional details such as shipping, tax.
-            $amount = new Amount();
-            if (isset($requestData['amount'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['amount']), $amount);
-            }
-
-            $detailArray = $this->checkEmptyObject((array)$details);
-            if ( !empty($detailArray) ) {
-                $amount->setDetails($details);
-            }
-
-            // ### Transaction
-            // A transaction defines the contract of a payment - what is the payment for and who is fulfilling it.
-            $transaction = new Transaction();
-            $amountArray = $this->checkEmptyObject((array)$amount);
-            if (!empty($amountArray)) {
-                $transaction->setAmount($amount);
-            }
-            $itemListArr = $this->checkEmptyObject((array)$itemList);
-            if (!empty($itemListArr)) {
-                $transaction->setItemList($itemList);
-            }
-
-            if (isset($requestData['transaction'])){
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['transaction']), $transaction);
-            }
-
-            if(isset($requestData['invoiceNumber'])){
-                $transaction->setInvoiceNumber($requestData['invoiceNumber']);
-            }
-
-            // ### Redirect urls
-            // Set the urls that the buyer must be redirected to after
-            // payment approval/ cancellation.
-            $baseUrl = isset($requestData['urls']['BaseUrl']) ? $requestData['urls']['BaseUrl'] : '';
-
-            $redirectUrls = new RedirectUrls();
-            if(isset($requestData['urls']['ReturnUrl'])){
-                $redirectUrls->setReturnUrl($baseUrl . $requestData['urls']['ReturnUrl']);
-            }
-            if(isset($requestData['urls']['CancelUrl'])){
-                $redirectUrls->setCancelUrl($baseUrl . $requestData['urls']['CancelUrl']);
-            }
-
-            // ### Future Payment
-
-            $payment = new FuturePayment();
-            $payment->setIntent($requestData['intent']);
-            $payment->setPayer($payer);
-            $payment->setRedirectUrls($redirectUrls);
-            $payment->setTransactions(array($transaction));
-
-            $authorizationCode  = $requestData['authorizationCode'];
-            $clientMetadataId = $requestData['clientMetadataId'];
-
-            $refreshToken = FuturePayment::getRefreshToken($authorizationCode, $this->_api_context);
-            $payment->updateAccessToken($refreshToken, $this->_api_context);
-
-            // ### Create Payment
-            // Create a payment by calling the payment->create() method with a valid ApiContext. The return object contains the state.
-            $requestArray = clone $payment;
-            $payment->create($this->_api_context,$clientMetadataId);
-
-            // ### Get redirect url
-            // The API response provides the url that you must redirect
-            // the buyer to. Retrieve the url from the $payment->getApprovalLink()
-            // method
-            $approvalUrl = $payment->getApprovalLink();
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYMENT'] = array('approvalUrl' => $approvalUrl, 'payment' => $payment->toArray());
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$payment->toJSON();
-            $paypal = new PayPal(array());
-            $paypal->TPV_Parse_Request($payment->toArray(), array(), 24, true, false, 'PayPal_Rest');
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Fetch Order array from the related resources  by passing the Payment id
-     * @param $payment_id  id of the Payment
-     * @return Array
-     *
-     */
-    public function GetOrderDetailsFromPaymentID($payment_id){
-
-        try{
-            $payment = Payment::get($payment_id, $this->_api_context);
-            $transactions = $payment->getTransactions();
-            $transaction = $transactions[0];
-            $relatedResources = $transaction->getRelatedResources();
-            $relatedResource = $relatedResources[0];
-            $order = $relatedResource->getOrder();
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['ORDER'] = $order->toArray();
-            return $returnArray;
-        }catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/angelleye/PayPal/rest/payouts/PayoutsAPI.php b/src/angelleye/PayPal/rest/payouts/PayoutsAPI.php
deleted file mode 100755
index ddec720a..00000000
--- a/src/angelleye/PayPal/rest/payouts/PayoutsAPI.php
+++ /dev/null
@@ -1,213 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use PayPal\Api\Currency;
-use PayPal\Api\Payout;
-use PayPal\Api\PayoutItem;
-use PayPal\Api\PayoutSenderBatchHeader;
-use \angelleye\PayPal\RestClass;
-
-/**
- * PayoutsAPI.
- * This class is responsible for Payouts APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class PayoutsAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     * Creates a payout.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function CreateSinglePayout($requestData) {
-        
-        try {
-            $payouts = new Payout();
-            $senderBatchHeader = new PayoutSenderBatchHeader();
-            if (isset($requestData['batchHeader'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['batchHeader']), $senderBatchHeader);
-            }
-            $senderItem = new PayoutItem();
-            if (isset($requestData['PayoutItem'])) {
-                $this->setArrayToMethods($this->checkEmptyObject($requestData['PayoutItem']), $senderItem);
-            }
-            $senderItem->setAmount(new Currency(json_encode($requestData['amount'])));
-
-            $senderBatchHeaderArray = $this->checkEmptyObject((array)$senderBatchHeader);
-            if (!empty($senderBatchHeaderArray)) {
-                $payouts->setSenderBatchHeader($senderBatchHeader);    
-            }
-
-            $senderItemArray = $this->checkEmptyObject((array)$senderItem);
-            if (!empty($senderItemArray)) {
-                $payouts->addItem($senderItem);
-            }   
-            $requestArray = clone $payouts;
-            $output = $payouts->createSynchronous($this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYOUT'] = $output->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Creates a batch payout.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function CreateBatchPayout($requestData){
-        
-        try {
-            $payouts = new Payout();
-
-            if(isset($requestData['batchHeader'])){
-                $senderBatchHeader = new PayoutSenderBatchHeader();
-                $this->setArrayToMethods(array_filter($requestData['batchHeader']), $senderBatchHeader);
-                if ($this->checkEmptyObject((array)$senderBatchHeader)) {
-                    $payouts->setSenderBatchHeader($senderBatchHeader);
-                }
-            }
-
-            if(isset($requestData['PayoutItem'])){
-                foreach ($requestData['PayoutItem'] as $value) {
-                    $senderItem = new PayoutItem();
-                    if (isset($value['amount'])){
-                        $senderItem->setAmount(new Currency(json_encode($value['amount'])));
-                        unset($value['amount']);
-                    }
-                    $this->setArrayToMethods(array_filter($value), $senderItem);
-                    $payouts->addItem($senderItem);
-                }
-            }
-            $requestArray = clone $payouts;
-            $output = $payouts->create(null,$this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['BATCH_PAYOUT'] = $output->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$output->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Get payout batch status.
-     *
-     * @param string $payoutBatchId
-     * @return array|object
-     */
-    public function GetPayoutBatchStatus($payoutBatchId){
-        try {
-            $output = Payout::get($payoutBatchId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['BATCH_STATUS'] = $output->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$payoutBatchId.'}';
-            $returnArray['RAWRESPONSE']=$output->toJSON();            
-           return $returnArray;              
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-    
-    /**
-     * Get payout item status.
-     *
-     * @param string $payoutItemId
-     * @return array|object
-     */
-    public function GetPayoutItemStatus($payoutItemId){
-        try {
-            $output = PayoutItem::get($payoutItemId, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYOUT_ITEM'] = $output->toArray();
-            $returnArray['RAWREQUEST']='{id:'.$payoutItemId.'}';
-            $returnArray['RAWRESPONSE']=$output->toJSON();     
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-    /**
-     * Cancels an unclaimed transaction. 
-     *
-     * @param string $payoutItemId
-     * @return array|object
-     */
-    public function CancelPayoutItem($payoutItemId){
-        try {
-            $PayoutItem = PayoutItem::get($payoutItemId, $this->_api_context);
-            if($PayoutItem->transaction_status == 'UNCLAIMED'){
-                 $output = PayoutItem::cancel($payoutItemId, $this->_api_context);                 
-                 $returnArray['RESULT'] = 'Success';
-                 $returnArray['CANCEL_PAYOUT_ITEM'] = $output->toArray();
-                 $returnArray['RAWREQUEST']='{id:'.$payoutItemId.'}';
-                 $returnArray['RAWRESPONSE']=$output->toJSON();
-                 return $returnArray;                                      
-            }
-            else{
-                return "Payout Item Status is not UNCLAIMED";
-            }           
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }   
-}
diff --git a/src/angelleye/PayPal/rest/paypal_sync/PayPalSyncAPI.php b/src/angelleye/PayPal/rest/paypal_sync/PayPalSyncAPI.php
deleted file mode 100644
index f21f73f0..00000000
--- a/src/angelleye/PayPal/rest/paypal_sync/PayPalSyncAPI.php
+++ /dev/null
@@ -1,86 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use \angelleye\PayPal\PayPalSyncClass;
-use \angelleye\PayPal\RestClass;
-
-/**
- * PayPalSyncAPI.
- * This class is responsible for PayPalSync APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class PayPalSyncAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     * Lists transactions.
-     *
-     * @param array $parameters
-     * @return array|object
-     */
-    public function PaypalSyncTransactions($parameters) {
-        try {
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $disputes = PayPalSyncClass::transactions($params, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['TRANSACTIONS'] = $disputes->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray;
-            $returnArray['RAWRESPONSE'] = $disputes->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-}
diff --git a/src/angelleye/PayPal/rest/referenced_payouts/ReferencedPayoutsAPI.php b/src/angelleye/PayPal/rest/referenced_payouts/ReferencedPayoutsAPI.php
deleted file mode 100644
index 88291bbf..00000000
--- a/src/angelleye/PayPal/rest/referenced_payouts/ReferencedPayoutsAPI.php
+++ /dev/null
@@ -1,87 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use \angelleye\PayPal\ReferencedPayoutsClass;
-use \angelleye\PayPal\RestClass;
-
-/**
- * ReferencedPayoutsAPI.
- * This class is responsible for Referenced Payouts APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class ReferencedPayoutsAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }
-
-    /**
-     * Creates a referenced batch payout for asynchronous, offline processing. Include a sender_batch_header object and an items array in the request URI.
-     *
-     * @param array $parameters
-     * @return array|object
-     */
-    public function CreateReferencedBatchPayout($parameters) {
-         $referancePayoutObject = new ReferencedPayoutsClass();
-        try {
-            $params = array_filter($parameters);
-            $requestArray = json_encode($params);
-            $payouts = $referancePayoutObject->referenced_payouts($params, $this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['PAYOUTS'] = $payouts->toArray();
-            $returnArray['RAWREQUEST'] = $requestArray;
-            $returnArray['RAWRESPONSE'] = $payouts->toJSON();
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-
-}
diff --git a/src/angelleye/PayPal/rest/vault/CreditCardAPI.php b/src/angelleye/PayPal/rest/vault/CreditCardAPI.php
deleted file mode 100755
index 4fbc825c..00000000
--- a/src/angelleye/PayPal/rest/vault/CreditCardAPI.php
+++ /dev/null
@@ -1,219 +0,0 @@
-
- *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
- * @support         http://www.angelleye.com/product/premium-support/
- * @version			v2.0.4
- * @filesource
-*/
-
-use \angelleye\PayPal\RestClass;
-use PayPal\Api\CreditCard;
-
-/**
- * CreditCardAPI.
- * This class is responsible for CreditCard APIs & bridge class between the REST API class and Angelleye PayPal Library.
- *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
- */
-class CreditCardAPI extends RestClass {
-
-    /**
-     * Private vairable to fetch and return @PayPal\Rest\ApiContext object.
-     *
-     * @var \PayPal\Rest\ApiContext $_api_context 
-     */
-    private $_api_context;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$configArray Array structure providing config data
-	 * @return	void
-	 */
-    public function __construct($configArray) {        
-        parent::__construct($configArray);
-        $this->_api_context = $this->get_api_context();
-    }    
-    
-    /**
-     * Stores credit card details in the PayPal vault.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function StoreCreditCard($requestData){
-        $creditCard = new CreditCard();
-        
-        if (isset($requestData['creditCard'])) {
-            $this->setArrayToMethods($this->checkEmptyObject($requestData['creditCard']), $creditCard);
-        }
-        
-        if (isset($requestData['payerInfo'])) {
-            $this->setArrayToMethods($this->checkEmptyObject($requestData['payerInfo']), $creditCard);
-        }
-        
-        if (isset($requestData['billingAddress'])) {
-            $this->setArrayToMethods(array("BillingAddress"=>$this->checkEmptyObject($requestData['billingAddress'])), $creditCard);
-        }
-        if (isset($requestData['optionalArray'])) {
-            $this->setArrayToMethods($this->checkEmptyObject($requestData['optionalArray']), $creditCard);
-        }
-        try {
-            $requestArray = clone $creditCard;
-            $creditCard->create($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CREDITCARD']=$creditCard->toArray();
-            $returnArray['RAWREQUEST']=$requestArray->toJSON();
-            $returnArray['RAWRESPONSE']=$creditCard->toJSON();
-            return $returnArray;
-        }
-        catch (\PayPal\Exception\PayPalConnectionException $ex) {
-           return $this->createErrorResponse($ex);
-        }        
-    }
-    
-    /**
-     * Lists vaulted credit cards.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function ListCreditCards($requestData) {
-        $creditCard = new \PayPal\Api\CreditCard();
-        try {            
-            $params = array_filter($requestData);
-            $requestArray = json_encode($params);
-            $cards = $creditCard->all($params, $this->_api_context);            
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['CARDS'] = $cards->toArray();
-            $returnArray['RAWREQUEST']=$requestArray;
-            $returnArray['RAWRESPONSE']=$cards->toJSON();
-            return $returnArray;            
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);         
-        }
-    }
-    
-    /**
-     * Shows details for a vaulted credit card, by ID.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function GetCardDetails($requestData){
-        $creditCard = new CreditCard();
-            try {
-                $card = $creditCard->get($requestData['credit_card_id'], $this->_api_context);                
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['CREDITCARD']=$card->toArray();                
-                $returnArray['RAWREQUEST']='{id:'.$requestData['credit_card_id'].'}';
-                $returnArray['RAWRESPONSE']=$card->toJSON();
-                return $returnArray;
-            } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-                return $this->createErrorResponse($ex);
-            }                    
-    }
-    
-    /**
-     * Deletes a vaulted credit card, by ID.
-     *
-     * @param array $requestData
-     * @return array|object
-     */
-    public function DeleteCreditCard($requestData){
-        $creditCard = new \PayPal\Api\CreditCard();        
-        try {
-            $creditCard->setId($requestData['credit_card_id']);            
-            $result = $creditCard->delete($this->_api_context);
-            $returnArray['RESULT'] = 'Success';
-            $returnArray['DELETE']=$result;
-            $returnArray['RAWREQUEST']=$creditCard->toJSON();
-            $returnArray['RAWRESPONSE']=$result;
-            return $returnArray;
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }
-       
-    /**
-     * Updates information for a vaulted credit card, by ID. 
-     *
-     * @param array $requestData
-     * @param string $credit_card_id
-     * @return array|object
-     */
-    public function UpdateCreditCard($requestData,$credit_card_id){
-            $creditCard = new \PayPal\Api\CreditCard();    
-            $pathRequest = new \PayPal\Api\PatchRequest();
-        try {
-            $creditCard->setId($credit_card_id);
-            $id = $creditCard->getId();
-            $i=0;
-            foreach ($requestData as $value) {  
-                if(is_array($value['value'])){
-                    if(!empty($value['operation']) && !empty($value['path']) && count($value['value'])>3){
-                        $ob=(object)  array_filter($value['value']);
-                        $pathOperation = new \PayPal\Api\Patch();
-                        $pathOperation->setOp($value['operation'])
-                                         ->setPath("/".$value['path'])
-                                         ->setValue($ob);
-                        $pathRequest->addPatch($pathOperation);
-                        $i++;
-                    }
-                }
-                else{
-                    if(!empty($value['operation']) && !empty($value['path']) && !empty($value['value'])){
-                        $pathOperation = new \PayPal\Api\Patch();
-                        $pathOperation->setOp($value['operation'])
-                                         ->setPath("/".$value['path'])
-                                         ->setValue($value['value']);
-                        $pathRequest->addPatch($pathOperation);
-                        $i++;
-                    }
-                }
-            } 
-            if($i>0) {
-               
-                $card = $creditCard->update($pathRequest,$this->_api_context);
-                $returnArray['RESULT'] = 'Success';
-                $returnArray['CREDITCARD']=$card->toArray();         
-                $returnArray['RAWREQUEST']= $pathRequest->toJSON();
-                $returnArray['RAWRESPONSE']=$card->toJSON();
-                return $returnArray;                
-            }
-            else{
-                return "Fill Atleast One Array Field/Element";
-            }
-        } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-            return $this->createErrorResponse($ex);
-        }
-    }    
-}
diff --git a/templates/rest/billing_agreements/BillAgreementBalance.php b/templates/rest/billing_agreements/BillAgreementBalance.php
deleted file mode 100644
index b6d6b1c4..00000000
--- a/templates/rest/billing_agreements/BillAgreementBalance.php
+++ /dev/null
@@ -1,24 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';    // The ID of the agreement for which to bill the balance.
-$note = '';           // The reason for the agreement state change.
-
-$returnArray = $PayPal->BillAgreementBalance($agreementId,$note);
-
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/CancelBillingAgreement.php b/templates/rest/billing_agreements/CancelBillingAgreement.php
deleted file mode 100644
index 57d3eee3..00000000
--- a/templates/rest/billing_agreements/CancelBillingAgreement.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';                       // Required. The ID of the Billing Agreement for which to Suspend Billing Agreement.
-$note        = '';                       // Required.Reason for changing the state of the agreement. 
-
-$returnArray = $PayPal->CancelBillingAgreement($agreementId,$note);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php b/templates/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php
deleted file mode 100644
index 6540c390..00000000
--- a/templates/rest/billing_agreements/CreateBillingAgreementWithCreditCard.php
+++ /dev/null
@@ -1,73 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = '';                             // Required. Billing plan id that will be used to create a billing agreement.
-
-$agreement = array(
-    "State" => '',                        // State of the agreement.
-    "Name" => '',                         // Required. Name of the agreement.
-    "Description" => '',                  // Required. Description of the agreement.
-    "StartDate" => ''                     // Required. Start date of the agreement. Date format yyyy-MM-dd z, as defined in [ISO8601](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-
-$creditCard = array(
-    'Type' => '',                                           // Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-    'Number' => '',                                         // Required.  Credit card number.  No spaces or punctuation.  
-    'ExpireMonth' => '',                                    // Required.  Credit card expiration Month.  Format is MM
-    'ExpireYear' => '',                                     // Required.  Credit card expiration year.  Format is YYYY
-    'Cvv2' => '',                                           // Requirements determined by your PayPal account settings.  Security digits for credit card.                                     
-    'FirstName' => '',                                      // Cardholder's first name.
-    'LastName' => '',                                       // Cardholder's last name.  
-    'ExternalCustomerId' => '',                             // A unique identifier of the customer to whom this bank account belongs. Generated and provided by the facilitator. **This is now used in favor of `payer_id` when creating or using a stored funding instrument in the vault.
-    'MerchantId' => '',                                     // A user provided, optional convenvience field that functions as a unique identifier for the merchant on behalf of whom this credit card is being stored for. Note that this has no relation to PayPal merchant id  
-    'PayerId' => '',                                        // A unique identifier that you can assign and track when storing a credit card or using a stored credit card. This ID can help to avoid unintentional use or misuse of credit cards. This ID can be any value you would like to associate with the saved card, such as a UUID, username, or email address. Required when using a stored credit card if a payer_id was originally provided when storing the credit card in vault.
-    'ExternalCardId' => '',                                 // A unique identifier of the bank account resource. Generated and provided by the facilitator so it can be used to restrict the usage of the bank account to the specific merchant.        
-);
-
-$payer =array(
-    "PaymentMethod" => 'credit_card',                         // Valid Values: ["credit_card", "bank", "paypal", "pay_upon_invoice", "carrier", "alternate_payment"]. Payment method being used - PayPal Wallet payment, Bank Direct Debit  or Direct Credit card.    
-    "AccountType" => ''                                       // Valid Values: ["BUSINESS", "PERSONAL", "PREMIER"]. Type of account relationship payer has with PayPal. 
-);
-// Payerinfo is Required. 
-$payerInfo = array(
-    'email' => '',                                           // Email address representing the payer. 127 characters max.    
-    "first_name" => '',                                      // First name of the payer. 
-    "last_name" => '',                                       // Last name of the payer.
-);
-
-$shippingAddress = array(
-    "Line1" => '',                                          // Line 1 of the Address (eg. number, street, etc).
-    "Line2" => '',                                          // Optional line 2 of the Address (eg. suite, apt #, etc.). 
-    "City"  => '',                                          // City name.
-    "CountryCode" => '',                                    // 2 letter country code.
-    "PostalCode" => '',                                     // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-    "State" => '',                                          // 2 letter code for US states, and the equivalent for other countries.
-    "NormalizationStatus" => ''                             // Valid Values: ["UNKNOWN", "UNNORMALIZED_USER_PREFERRED", "NORMALIZED", "UNNORMALIZED"]. Address normalization status    
-);
-
-
-$requestData = array(
-        "planId"          => $planId,
-        "agreement"       => $agreement,
-        "creditCard"      => $creditCard,
-        "payer"           => $payer,
-        "payerInfo"       => $payerInfo ,
-        "shippingAddress" => $shippingAddress        
-);
-
-$returnArray = $PayPal->CreateBillingAgreementWithCreditCard($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/CreateBillingAgreementWithPayPal.php b/templates/rest/billing_agreements/CreateBillingAgreementWithPayPal.php
deleted file mode 100644
index b50ec9b1..00000000
--- a/templates/rest/billing_agreements/CreateBillingAgreementWithPayPal.php
+++ /dev/null
@@ -1,51 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = '';                            // Required. Billing plan id that will be used to create a billing agreement.
-
-$agreement = array(
-    "State" => '',                       // State of the agreement.
-    "Name" => '',                        // Required. Name of the agreement.
-    "Description" => '',                 // Required. Description of the agreement.
-    "StartDate" => ''                    // Required. Start date of the agreement. Date format yyyy-MM-dd z, as defined in [ISO8601](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-// Payerinfo is Required.
-$payer =array(
-    "PaymentMethod" => '',               // Valid Values: ["credit_card", "bank", "paypal", "pay_upon_invoice", "carrier", "alternate_payment"]. Payment method being used - PayPal Wallet payment, Bank Direct Debit  or Direct Credit card.    
-    "AccountType" => ''                  // Valid Values: ["BUSINESS", "PERSONAL", "PREMIER"]. Type of account relationship payer has with PayPal. 
-);
-
-$shippingAddress = array(
-    "Line1" => '',                                          // Line 1 of the Address (eg. number, street, etc).
-    "Line2" => '',                                          // Optional line 2 of the Address (eg. suite, apt #, etc.). 
-    "City"  => '',                                          // City name.
-    "CountryCode" => '',                                    // 2 letter country code.
-    "PostalCode" => '',                                     // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-    "State" => '',                                          // 2 letter code for US states, and the equivalent for other countries.
-    "NormalizationStatus" => ''                             // Valid Values: ["UNKNOWN", "UNNORMALIZED_USER_PREFERRED", "NORMALIZED", "UNNORMALIZED"]. Address normalization status    
-);
-
-
-$requestData = array(
-        "planId"          => $planId,
-        "agreement"       => $agreement,       
-        "payer"           => $payer,       
-        "shippingAddress" => $shippingAddress        
-);
-
-$returnArray = $PayPal->CreateBillingAgreementWithPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/ExecuteAgreement.php b/templates/rest/billing_agreements/ExecuteAgreement.php
deleted file mode 100644
index 00a52836..00000000
--- a/templates/rest/billing_agreements/ExecuteAgreement.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-    $token = isset($_GET['token']) ? $_GET['token'] : '';
-    $result = $PayPal->ExecuteAgreement($token);
-    echo "
";
-    print_r($result);
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
\ No newline at end of file
diff --git a/templates/rest/billing_agreements/GetBillingAgreement.php b/templates/rest/billing_agreements/GetBillingAgreement.php
deleted file mode 100644
index 2ffc2fff..00000000
--- a/templates/rest/billing_agreements/GetBillingAgreement.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';                       // Required. The ID of the Billing Agreement for which to show details.
-
-$returnArray = $PayPal->GetBillingAgreement($agreementId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/ReactivateBillingAgreement.php b/templates/rest/billing_agreements/ReactivateBillingAgreement.php
deleted file mode 100644
index 587f0dc2..00000000
--- a/templates/rest/billing_agreements/ReactivateBillingAgreement.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';                       // Required. The ID of the Billing Agreement for which to Suspend Billing Agreement.
-$note        = '';                       // Required. Reason for changing the state of the agreement. 
-
-$returnArray = $PayPal->ReactivateBillingAgreement($agreementId,$note);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/SearchBillingTransactions.php b/templates/rest/billing_agreements/SearchBillingTransactions.php
deleted file mode 100644
index e2863ecf..00000000
--- a/templates/rest/billing_agreements/SearchBillingTransactions.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';                                      // Identifier of the agreement resource for which to list transactions.
-
-$params = array(
-                'start_date' => '',                     // Format : yyyy-mm-dd . The start date of the range of transactions to list.
-                'end_date'   => ''                      // Format : yyyy-mm-dd . The end date of the range of transactions to list. 
-          );
-
-$returnArray = $PayPal->SearchBillingTransactions($agreementId,$params);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/SetAgreementBalance.php b/templates/rest/billing_agreements/SetAgreementBalance.php
deleted file mode 100644
index 2d2d628a..00000000
--- a/templates/rest/billing_agreements/SetAgreementBalance.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';  // The ID of the agreement for which to set a balance.
-
-$amount = array(
-    'Currency' => '',
-    'value' => ''
-);
-
-$returnArray = $PayPal->SetAgreementBalance($agreementId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/SuspendBillingAgreement.php b/templates/rest/billing_agreements/SuspendBillingAgreement.php
deleted file mode 100644
index c4d98690..00000000
--- a/templates/rest/billing_agreements/SuspendBillingAgreement.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreementId = '';                       // Required. The ID of the Billing Agreement for which to Suspend Billing Agreement.
-$note        = '';                       // Required. Reason for changing the state of the agreement. 
-
-$returnArray = $PayPal->SuspendBillingAgreement($agreementId,$note);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_agreements/UpdateBillingAgreement.php b/templates/rest/billing_agreements/UpdateBillingAgreement.php
deleted file mode 100644
index cfca727d..00000000
--- a/templates/rest/billing_agreements/UpdateBillingAgreement.php
+++ /dev/null
@@ -1,34 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$agreement_id  = '';                                // Required. Identifier of the agreement resource to update.
-
-$agreement = array(
-    "description" => '',                            // Description of the agreement.   
-    "shipping_address" => array(
-        "line1" => '',                              // Line 1 of the Address (eg. number, street, etc).
-        "line2" => '',                              // Optional line 2 of the Address (eg. suite, apt #, etc.). 
-        "city"  => '',                              // City name.
-        "country_code" => '',                       // 2 letter country code.
-        "postal_code" => '',                        // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code.
-        "state" => '',                              // 2 letter code for US states, and the equivalent for other countries.        
-    )
-);
-
-
-
-$returnArray = $PayPal->UpdateBillingAgreement($agreement_id,$agreement);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_plans/CreatePlan.php b/templates/rest/billing_plans/CreatePlan.php
deleted file mode 100644
index 892f745c..00000000
--- a/templates/rest/billing_plans/CreatePlan.php
+++ /dev/null
@@ -1,107 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$plan = array(
-    'Name' => '',                                   // Required. Name of the billing plan. 128 characters max.
-    'Description' => '',                            // Required. Description of the billing plan. 128 characters max.
-    'Type' => '',                                   // Required. Type of the billing plan. Allowed values: `FIXED`, `INFINITE`.
-    'CreateTime' => '',                             // Time when the billing plan was created. Format YYYY-MM-DDTimeTimezone, as defined in [ISO8601](http://tools.ietf.org/html/rfc3339#section-5.6).
-);
-// Payment Definition is Required for creating Plan.
-$paymentDefinitions[0] = array(
-    'Name' => '',                                  // Name of the payment definition. 128 characters max.
-    'Type' => '',                                  // Allowed values: `TRIAL`, `REGULAR`. Type of the payment definition.
-    'FrequencyInterval' => '',                     // How frequently the customer should be charged.
-    'Frequency' => '',                             // Allowed values: `WEEK`, `DAY`, `YEAR`, `MONTH`. Frequency of the payment definition offered.
-    'Cycles' => '',                                // Number of cycles in this payment definition.
-    'Amount' => array(
-        'value' => '',                             // Amount that will be charged at the end of each cycle for this payment definition.
-        'currency' => ''                           // Three Letter Currency code.
-    ),
-    'ChargeModels' => array(
-        0 => array(
-            'Type' => 'SHIPPING',                  // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => '',                     // Amount to charge.
-                'currency' => ''                   // Three Letter Currency code.
-            )
-        ),
-        1 => array(
-            'Type' => 'TAX',                       // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => '',                     // Amount to charge.
-                'currency' => ''                   // Three Letter Currency code.
-            )
-        )
-    )
-);
-
-$paymentDefinitions[1] = array(
-    'Name' => '',                                  // Name of the payment definition. 128 characters max.
-    'Type' => '',                                  // Allowed values: `TRIAL`, `REGULAR`. Type of the payment definition.
-    'FrequencyInterval' => '',                     // How frequently the customer should be charged.
-    'Frequency' => '',                             // Allowed values: `WEEK`, `DAY`, `YEAR`, `MONTH`. Frequency of the payment definition offered.
-    'Cycles' => '',                                // Number of cycles in this payment definition.
-    'Amount' => array(
-        'value' => '',                             // Amount that will be charged at the end of each cycle for this payment definition.
-        'currency' => ''                           // Three Letter Currency code.
-    ),
-    'ChargeModels' => array(
-        0 => array(
-            'Type' => 'SHIPPING',                  // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => '',                     // Amount to charge.
-                'currency' => ''                   // Three Letter Currency code.
-            )
-        ),
-        1 => array(
-            'Type' => 'TAX',                       // Allowed values: `SHIPPING`, `TAX`. Type of charge model.
-            'Amount' => array(
-                'value' => '',                     // Amount to charge.
-                'currency' => ''                   // Three Letter Currency code.
-            )
-        )
-    )
-);
-
-$baseUrl = '';                                     // Base URL of your directory.
-$CancelUrl = '';                                   // Redirect URL on cancellation of agreement request. 1000 characters max.
-$ReturnUrl = '';                                   // Redirect URL on creation of agreement request. 1000 characters max.
-// Merchant Preferences are optional for creating plan.
-$merchant_preferences = array(
-    "NotifyUrl" => '',                             // Notify URL on agreement creation. 1000 characters max.
-    "MaxFailAttempts" => '',                       // Total number of failed attempts allowed. Default is 0, representing an infinite number of failed attempts.
-    "AutoBillAmount" => '',                        // Allowed values: `YES`, `NO`. Default is `NO`. Allow auto billing for the outstanding amount of the agreement in the next cycle.
-    "InitialFailAmountAction" => '',               // Allowed values: `CONTINUE`, `CANCEL`. Default is continue. Action to take if a failure occurs during initial payment.
-    "AcceptedPaymentType" => '',                   // Payment types that are accepted for this plan.
-    "SetupFee" => array(
-        'value' => '',                             // Setup fee amount. Default is 0.
-        'currency' => ''                           // Three Letter Currency code.
-    )
-);
-
-$requestData = array(
-    "plan" => $plan,
-    "paymentDefinition" => $paymentDefinitions,
-    "merchant_preferences" => $merchant_preferences,
-    "baseUrl" => $baseUrl,
-    "CancelUrl" => $CancelUrl,
-    "ReturnUrl" => $ReturnUrl
-);
-
-$returnArray = $PayPal->CreatePlan($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_plans/DeletePlan.php b/templates/rest/billing_plans/DeletePlan.php
deleted file mode 100644
index 0ccbc0d4..00000000
--- a/templates/rest/billing_plans/DeletePlan.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = '';                       // Required. The ID of the billing plan for delete.
-
-$returnArray = $PayPal->DeletePlan($planId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_plans/GetPlan.php b/templates/rest/billing_plans/GetPlan.php
deleted file mode 100644
index 70d6c238..00000000
--- a/templates/rest/billing_plans/GetPlan.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planId = '';                       // Required. The ID of the billing plan for which to show details.
-
-$returnArray = $PayPal->GetPlan($planId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_plans/ListPlans.php b/templates/rest/billing_plans/ListPlans.php
deleted file mode 100644
index ba6eb45b..00000000
--- a/templates/rest/billing_plans/ListPlans.php
+++ /dev/null
@@ -1,25 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$parameters = array(
-    'page_size'      => '',                // The number of billing plans to list on a single page. For example, if page_size is 10, each page shows ten billing plans. A valid value is a non-negative, non-zero integer. Default is 10.
-    'page'           => '',                // The zero-indexed number of the first page to return to begin the set of pages that are returned in the response. Default is 0.
-    'status'         => '',                // Possible values: CREATED, ACTIVE, INACTIVE, DELETED. Filters the billing plans in the response by a plan status. Value is CREATED for created plans, ACTIVE for active plans, INACTIVE for inactive plans, or DELETED for deleted plans.
-    'total_required' => ''                 // Value is yes or no. Indicates whether to return the total_items and total_pages fields in the response.  
-);
-
-$returnArray = $PayPal->ListPlans($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/billing_plans/UpdatePlan.php b/templates/rest/billing_plans/UpdatePlan.php
deleted file mode 100644
index 9e7b2717..00000000
--- a/templates/rest/billing_plans/UpdatePlan.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\billing\BillingAPI($configArray);
-
-$planid = '';                                  // Required. The ID of the billing plan to update. 
-
-$state = '';                                   // Allowed values: CREATED, ACTIVE, INACTIVE, and DELETED. Status of the billing plan.
-
-$items = array(
-    'op'      => '',                           // Possible values: add, remove, replace, move, copy, test. The operation to perform.
-    'path'    => '',                           // A JSON pointer. References a location in the target document where the operation is performed.
-);
-
-$returnArray = $PayPal->UpdatePlan($planid,$items,$state);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/checkout_orders/AuthorizeOrder.php b/templates/rest/checkout_orders/AuthorizeOrder.php
deleted file mode 100644
index 21ac6d32..00000000
--- a/templates/rest/checkout_orders/AuthorizeOrder.php
+++ /dev/null
@@ -1,45 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-
-/**
- * Authorizes payment for an order.
- */
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    /**
-     * You can make this call only if you specified intent=AUTHORIZE in the create order call.
-     * get order id after the payment approval from PayPal,
-     * but if you know Order id then you can directly use $order_id function to AUTHORIZE the order.
-     */
-
-    $order_id = isset($_GET['token']) ? $_GET['token'] : '';            // Required. The ID of the order for which to authorize.
-
-    $response = $PayPal->AuthorizeOrder($order_id);
-
-    echo "
";
-    print_r($response);
-    exit;
-
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
-
diff --git a/templates/rest/checkout_orders/CaptureAuthorizedPayment.php b/templates/rest/checkout_orders/CaptureAuthorizedPayment.php
deleted file mode 100644
index 14514a0c..00000000
--- a/templates/rest/checkout_orders/CaptureAuthorizedPayment.php
+++ /dev/null
@@ -1,69 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id  = '';       // The PayPal-generated ID for the authorized payment to capture.
-
-/**
- *   To capture a portion of the full authorized amount, specify an amount.
- *   If amount is not specified, the full authorized amount is captured.
- *   The amount must be a positive number and in the same currency as the
- *   authorization against which the payment is being captured.
- */
-$amount = array(
-    'currency_code' => '',
-    'value' => '',              // The amount to capture.
-);
-
-$final_capture = '';            // Default : false , Indicates whether you can make additional captures against the authorized payment. Set to true if you do not intend to capture additional payments against the authorization. Set to false if you intend to capture additional payments against the authorization.
-
-$invoice_id  = '';              // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
-
-/**
- * Any additional payment instructions for PayPal for Partner customers.
- * Enables features for partners and marketplaces, such as delayed disbursement and collection of a platform fee.
- * Applies during order creation for captured payments or during capture of authorized payments.
-$payment_instruction  = array(
-    'disbursement_mode' => '',
-    'platform_fees' => array(
-        'amount' => array(
-            'currency_code' => '',
-            'value' => ''
-        ),
-        'payee' => array(
-            'email_address' => '',
-            'merchant_id' => ''
-        )
-    )
-);
- */
-
-$requestArray = array(
-
-    'amount' => $amount,
-    'final_capture' => $final_capture,
-    'invoice_id' => $invoice_id,
-    //'payment_instruction' => $payment_instruction
-);
-
-
-$response = $PayPal->CaptureAuthorizedPayment($authorization_id,$requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/CaptureOrder.php b/templates/rest/checkout_orders/CaptureOrder.php
deleted file mode 100644
index 9f230294..00000000
--- a/templates/rest/checkout_orders/CaptureOrder.php
+++ /dev/null
@@ -1,43 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    /**
-     * get order id after the payment approval from PayPal,
-     * but if you know Order id then you can directly use $order_id function to capture the order.
-     */
-
-    /**
-     * Order state must be APPROVED for capturing an order.
-     */
-    $order_id = isset($_GET['token']) ? $_GET['token'] : '';            // Required
-
-    $response = $PayPal->CaptureOrder($order_id);
-
-    echo "
";
-    print_r($response);
-    exit;
-
-}
-else{
-    echo "User Cancelled the Approval";
-    exit;
-}
-
diff --git a/templates/rest/checkout_orders/CreateAuthorizeOrder.php b/templates/rest/checkout_orders/CreateAuthorizeOrder.php
deleted file mode 100644
index b110fd40..00000000
--- a/templates/rest/checkout_orders/CreateAuthorizeOrder.php
+++ /dev/null
@@ -1,211 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-/**
- * The intent to either capture payment immediately or authorize a payment for an order after order creation.
- * allowed values are: CAPTURE , AUTHORIZE
- * CAPTURE. The merchant intends to capture payment immediately after the customer makes a payment.
- * AUTHORIZE. The merchant intends to authorize a payment and place funds on hold after the customer makes a payment. Authorized payments are guaranteed for up to three days but are available to capture for up to 29 days. After the three-day honor period, the original authorized payment expires and you must re-authorize the payment. You must make a separate request to capture payments on demand.
- */
-
-$intent = '';                       // Required
-
-$currency = '';                     // The three-character ISO-4217 currency code that identifies the currency. https://developer.paypal.com/docs/integration/direct/rest/currency-codes/
-
-$items[0] = array(
-    'sku'         => '',            // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => '',            // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => '',            // The detailed item description. Maximum length: 127.
-    'quantity'    => '',            // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(         // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'tax'         => array(         // The item tax for each unit.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'category'    => ''             // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$items[1] = array(
-    'sku'         => '',            // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => '',            // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => '',            // The detailed item description. Maximum length: 127.
-    'quantity'    => '',            // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(         // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'tax'         => array(         // The item tax for each unit.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'category'    => ''             // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$orderItems = $items;
-
-$amount = array(
-    'currency_code' => $currency,
-    'value' => '',
-    'breakdown' => array(
-        'item_total' => array(          // The subtotal for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'shipping' => array(            // The shipping fee for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'handling' => array(            // The handling fee for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'tax_total' => array(            // The total tax for all items.
-            'value' =>'',
-            'currency_code' => $currency
-        ),
-        'insurance' => array(            // The insurance fee for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'shipping_discount' => array(    // The shipping discount for all items.
-            'value' => '',
-            'currency_code' => $currency
-        )
-    )
-);
-
-/**
- * For shipping_preferences
- * The possible values are:
- *   GET_FROM_FILE  -  Use the customer-provided shipping address on the PayPal site.
- *   NO_SHIPPING -  Redact the shipping address from the PayPal site. Recommended for digital goods.
- *   SET_PROVIDED_ADDRESS - Use the merchant-provided address. The customer cannot change this address on the PayPal site.
- *
- *   note : if you select SET_PROVIDED_ADDRESS then you should pass $shipping array that we have in sample as commented code
- *
- */
-
-/**
- * For landing_page , The type of landing page to show on the PayPal site for customer checkout.
- * The possible values are :
- *       LOGIN -   Default. When the customer clicks PayPal Checkout, the customer is redirected to a page to log in to PayPal and approve the payment.
- *       BILLING - When the customer clicks PayPal Checkout, the customer is redirected to a page to enter credit or debit card and other relevant billing information required to complete the purchase.
- */
-
-/**
- *  For user_action, Configures a Continue or Pay Now checkout flow.
- *  CONTINUE -  After you redirect the customer to the PayPal payment page, a Continue button appears. Use this option when the final amount is not known when the checkout flow is initiated and you want to redirect the customer to the merchant page without processing the payment.
- *  PAY_NOW - After you redirect the customer to the PayPal payment page, a Pay Now button appears. Use this option when the final amount is known when the checkout is initiated and you want to process the payment immediately when the customer clicks Pay Now.
- */
-
-$application_context = array(
-    'brand_name' => '',              // The label that overrides the business name in the PayPal account on the PayPal site.
-    'locale' => '',                  // PayPal supports a five-character code.
-    'landing_page' => '',            // Allowed Values : LOGIN,BILLING
-    'shipping_preferences' => '',    // Allowed Values : GET_FROM_FILE , NO_SHIPPING , SET_PROVIDED_ADDRESS
-    'user_action' => '',             // Configures a Continue or Pay Now checkout flow.
-    'payment_method' => array(
-        'payer_selected' => '',      // Values : PAYPAL,PAYPAL_CREDIT. The customer and merchant payment preferences.
-        'payee_preferred' => ''      // Values : UNRESTRICTED , IMMEDIATE_PAYMENT_REQUIRED
-    ),
-    'return_url' => '',              // The URL where the customer is redirected after the customer approves the payment.
-    'cancel_url' => '',              // The URL where the customer is redirected after the customer cancels the payment.
-);
-
-/*
- *
- * Uncomment if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-$shipping = array(
-                'method' => 'United States Postal Service',
-                'name' => array(
-                    'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-                    'prefix' => '',              // The prefix, or title, to the party's name.
-                    'given_name' => '',          // When the party is a person, the party's given, or first, name.
-                    'surname' => '',             // When the party is a person, the party's surname or family name.
-                    'middle_name' => '',         // When the party is a person, the party's middle name.
-                    'suffix' => ''               // The suffix for the party's name.
-                ),
-                'address' => array(
-                    'address_line_1' => '123 Townsend St',
-                    'address_line_2' => 'Floor 6',
-                    'admin_area_2' => 'San Francisco',     // A city, town, or village.
-                    'admin_area_1' => 'CA',                // country
-                    'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-                    'country_code' => 'US',                // The country code.
-                ),
-            );
-*/
-
-/*
- * Payer object is optional , if you have buyer details and you want to pass it then you can uncomment the code and use $payer in request
- *
-$payer = array(             // The customer who approves and pays for the order. The customer is also known as the payer.
-    'email_address' => 'test_buyer@domain.com', // The email address of the payer.
-    'name' => array(
-        'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-        'prefix' => '',              // The prefix, or title, to the party's name.
-        'given_name' => '',          // When the party is a person, the party's given, or first, name.
-        'surname' => '',             // When the party is a person, the party's surname or family name.
-        'middle_name' => '',         // When the party is a person, the party's middle name.
-        'suffix' => ''               // The suffix for the party's name.
-    ),
-    'phone' => array(                // The phone number of the customer. Available only when you enable the Contact Telephone Number option in the Profile & Settings for the merchant's PayPal account.
-        'phone_type' => '',          // The phone type. FAX, HOME, MOBILE, OTHER, PAGER.
-        'phone_number' => array(
-            'national_number' => '', // The phone number, in its canonical international E.164 numbering plan format. Supports only the national_number property.
-        )
-    ),
-    'birth_date' => '',              // The birth date of the payer in YYYY-MM-DD format.
-    'address' => array(
-        'address_line_1' => '123 Townsend St',
-        'address_line_2' => 'Floor 6',
-        'admin_area_2' => 'San Francisco',     // A city, town, or village.
-        'admin_area_1' => 'CA',                // country
-        'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-        'country_code' => 'US',                // The country code.
-    )
-);
-*/
-
-$purchase_units  = array(
-    'reference_id' => '',           // The ID for the purchase unit. Required for multiple purchase_units or if an order must be updated by using PATCH. If you omit the reference_id for an order with one purchase unit, PayPal sets the reference_id to default.
-    'description' => '',            // The purchase description. Maximum length: 127.
-    'custom_id' => '',              // The API caller-provided external ID. Used to reconcile client transactions with PayPal transactions. Appears in transaction and settlement reports but is not visible to the payer.
-    'soft_descriptor' => '',        // The payment descriptor on the payer's credit card statement. Maximum length: 22.
-    'invoice_id' => '',             // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. Maximum length: 127.
-    'amount' => $amount,
-    //'shipping' => $shipping,      // Add $shipping if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-    'items' => $orderItems
-);
-
-$requestArray = array(
-    'intent'=>$intent,
-    'application_context' => $application_context,
-    'purchase_units' => $purchase_units,
-    //'payer' => $payer
-);
-
-$response = $PayPal->CreateOrder($requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/CreateCaptureOrder.php b/templates/rest/checkout_orders/CreateCaptureOrder.php
deleted file mode 100644
index b110fd40..00000000
--- a/templates/rest/checkout_orders/CreateCaptureOrder.php
+++ /dev/null
@@ -1,211 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-/**
- * The intent to either capture payment immediately or authorize a payment for an order after order creation.
- * allowed values are: CAPTURE , AUTHORIZE
- * CAPTURE. The merchant intends to capture payment immediately after the customer makes a payment.
- * AUTHORIZE. The merchant intends to authorize a payment and place funds on hold after the customer makes a payment. Authorized payments are guaranteed for up to three days but are available to capture for up to 29 days. After the three-day honor period, the original authorized payment expires and you must re-authorize the payment. You must make a separate request to capture payments on demand.
- */
-
-$intent = '';                       // Required
-
-$currency = '';                     // The three-character ISO-4217 currency code that identifies the currency. https://developer.paypal.com/docs/integration/direct/rest/currency-codes/
-
-$items[0] = array(
-    'sku'         => '',            // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => '',            // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => '',            // The detailed item description. Maximum length: 127.
-    'quantity'    => '',            // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(         // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'tax'         => array(         // The item tax for each unit.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'category'    => ''             // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$items[1] = array(
-    'sku'         => '',            // Stock keeping unit corresponding (SKU) to item.Maximum length: 127.
-    'name'        => '',            // Required if you are adding item array. The item name or title. 127 characters max.
-    'description' => '',            // The detailed item description. Maximum length: 127.
-    'quantity'    => '',            // The item quantity. Must be a whole number. Maximum length: 10.
-    'unit_amount' => array(         // Required if you are adding item array. The item price or rate per unit. 32 characters max.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'tax'         => array(         // The item tax for each unit.
-        'value' => '',
-        'currency_code' => $currency
-    ),
-    'category'    => ''             // The item category type. DIGITAL_GOODS | PHYSICAL_GOODS
-);
-
-$orderItems = $items;
-
-$amount = array(
-    'currency_code' => $currency,
-    'value' => '',
-    'breakdown' => array(
-        'item_total' => array(          // The subtotal for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'shipping' => array(            // The shipping fee for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'handling' => array(            // The handling fee for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'tax_total' => array(            // The total tax for all items.
-            'value' =>'',
-            'currency_code' => $currency
-        ),
-        'insurance' => array(            // The insurance fee for all items.
-            'value' => '',
-            'currency_code' => $currency
-        ),
-        'shipping_discount' => array(    // The shipping discount for all items.
-            'value' => '',
-            'currency_code' => $currency
-        )
-    )
-);
-
-/**
- * For shipping_preferences
- * The possible values are:
- *   GET_FROM_FILE  -  Use the customer-provided shipping address on the PayPal site.
- *   NO_SHIPPING -  Redact the shipping address from the PayPal site. Recommended for digital goods.
- *   SET_PROVIDED_ADDRESS - Use the merchant-provided address. The customer cannot change this address on the PayPal site.
- *
- *   note : if you select SET_PROVIDED_ADDRESS then you should pass $shipping array that we have in sample as commented code
- *
- */
-
-/**
- * For landing_page , The type of landing page to show on the PayPal site for customer checkout.
- * The possible values are :
- *       LOGIN -   Default. When the customer clicks PayPal Checkout, the customer is redirected to a page to log in to PayPal and approve the payment.
- *       BILLING - When the customer clicks PayPal Checkout, the customer is redirected to a page to enter credit or debit card and other relevant billing information required to complete the purchase.
- */
-
-/**
- *  For user_action, Configures a Continue or Pay Now checkout flow.
- *  CONTINUE -  After you redirect the customer to the PayPal payment page, a Continue button appears. Use this option when the final amount is not known when the checkout flow is initiated and you want to redirect the customer to the merchant page without processing the payment.
- *  PAY_NOW - After you redirect the customer to the PayPal payment page, a Pay Now button appears. Use this option when the final amount is known when the checkout is initiated and you want to process the payment immediately when the customer clicks Pay Now.
- */
-
-$application_context = array(
-    'brand_name' => '',              // The label that overrides the business name in the PayPal account on the PayPal site.
-    'locale' => '',                  // PayPal supports a five-character code.
-    'landing_page' => '',            // Allowed Values : LOGIN,BILLING
-    'shipping_preferences' => '',    // Allowed Values : GET_FROM_FILE , NO_SHIPPING , SET_PROVIDED_ADDRESS
-    'user_action' => '',             // Configures a Continue or Pay Now checkout flow.
-    'payment_method' => array(
-        'payer_selected' => '',      // Values : PAYPAL,PAYPAL_CREDIT. The customer and merchant payment preferences.
-        'payee_preferred' => ''      // Values : UNRESTRICTED , IMMEDIATE_PAYMENT_REQUIRED
-    ),
-    'return_url' => '',              // The URL where the customer is redirected after the customer approves the payment.
-    'cancel_url' => '',              // The URL where the customer is redirected after the customer cancels the payment.
-);
-
-/*
- *
- * Uncomment if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-$shipping = array(
-                'method' => 'United States Postal Service',
-                'name' => array(
-                    'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-                    'prefix' => '',              // The prefix, or title, to the party's name.
-                    'given_name' => '',          // When the party is a person, the party's given, or first, name.
-                    'surname' => '',             // When the party is a person, the party's surname or family name.
-                    'middle_name' => '',         // When the party is a person, the party's middle name.
-                    'suffix' => ''               // The suffix for the party's name.
-                ),
-                'address' => array(
-                    'address_line_1' => '123 Townsend St',
-                    'address_line_2' => 'Floor 6',
-                    'admin_area_2' => 'San Francisco',     // A city, town, or village.
-                    'admin_area_1' => 'CA',                // country
-                    'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-                    'country_code' => 'US',                // The country code.
-                ),
-            );
-*/
-
-/*
- * Payer object is optional , if you have buyer details and you want to pass it then you can uncomment the code and use $payer in request
- *
-$payer = array(             // The customer who approves and pays for the order. The customer is also known as the payer.
-    'email_address' => 'test_buyer@domain.com', // The email address of the payer.
-    'name' => array(
-        'full_name' => 'Test Buyer', // When the party is a person, the party's full name.
-        'prefix' => '',              // The prefix, or title, to the party's name.
-        'given_name' => '',          // When the party is a person, the party's given, or first, name.
-        'surname' => '',             // When the party is a person, the party's surname or family name.
-        'middle_name' => '',         // When the party is a person, the party's middle name.
-        'suffix' => ''               // The suffix for the party's name.
-    ),
-    'phone' => array(                // The phone number of the customer. Available only when you enable the Contact Telephone Number option in the Profile & Settings for the merchant's PayPal account.
-        'phone_type' => '',          // The phone type. FAX, HOME, MOBILE, OTHER, PAGER.
-        'phone_number' => array(
-            'national_number' => '', // The phone number, in its canonical international E.164 numbering plan format. Supports only the national_number property.
-        )
-    ),
-    'birth_date' => '',              // The birth date of the payer in YYYY-MM-DD format.
-    'address' => array(
-        'address_line_1' => '123 Townsend St',
-        'address_line_2' => 'Floor 6',
-        'admin_area_2' => 'San Francisco',     // A city, town, or village.
-        'admin_area_1' => 'CA',                // country
-        'postal_code' => '94107',              // The postal code, which is the zip code or equivalent
-        'country_code' => 'US',                // The country code.
-    )
-);
-*/
-
-$purchase_units  = array(
-    'reference_id' => '',           // The ID for the purchase unit. Required for multiple purchase_units or if an order must be updated by using PATCH. If you omit the reference_id for an order with one purchase unit, PayPal sets the reference_id to default.
-    'description' => '',            // The purchase description. Maximum length: 127.
-    'custom_id' => '',              // The API caller-provided external ID. Used to reconcile client transactions with PayPal transactions. Appears in transaction and settlement reports but is not visible to the payer.
-    'soft_descriptor' => '',        // The payment descriptor on the payer's credit card statement. Maximum length: 22.
-    'invoice_id' => '',             // The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives. Maximum length: 127.
-    'amount' => $amount,
-    //'shipping' => $shipping,      // Add $shipping if you have shipping_preferences as SET_PROVIDED_ADDRESS in application context.
-    'items' => $orderItems
-);
-
-$requestArray = array(
-    'intent'=>$intent,
-    'application_context' => $application_context,
-    'purchase_units' => $purchase_units,
-    //'payer' => $payer
-);
-
-$response = $PayPal->CreateOrder($requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/GetAuthorizePaymentDetails.php b/templates/rest/checkout_orders/GetAuthorizePaymentDetails.php
deleted file mode 100644
index fe439852..00000000
--- a/templates/rest/checkout_orders/GetAuthorizePaymentDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id = '';        // The ID of the authorized payment for which to show details.
-
-$response = $PayPal->GetAuthorizePaymentDetails($authorization_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/GetCapturedPaymentDetails.php b/templates/rest/checkout_orders/GetCapturedPaymentDetails.php
deleted file mode 100644
index 3e4d48e7..00000000
--- a/templates/rest/checkout_orders/GetCapturedPaymentDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$capture_id = '';      // The PayPal-generated ID for the captured payment for which to show details.
-
-$response = $PayPal->GetCapturedPaymentDetails($capture_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/GetOrderDetails.php b/templates/rest/checkout_orders/GetOrderDetails.php
deleted file mode 100644
index 86473513..00000000
--- a/templates/rest/checkout_orders/GetOrderDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$order_id = '';        // The ID of the order for which to show details.
-
-$response = $PayPal->GetOrderDetails($order_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/Reauthorize.php b/templates/rest/checkout_orders/Reauthorize.php
deleted file mode 100644
index 2a0b7d5f..00000000
--- a/templates/rest/checkout_orders/Reauthorize.php
+++ /dev/null
@@ -1,30 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id  = '';       // The PayPal-generated ID for the authorized payment to reauthorize.
-
-$amount = array(               // The amount to reauthorize for an authorized payment.
-    'currency_code' => '',
-    'value' => ''
-);
-$response = $PayPal->Reauthorize($authorization_id,$amount);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/RefundCapturedPayment.php b/templates/rest/checkout_orders/RefundCapturedPayment.php
deleted file mode 100644
index 88a658c6..00000000
--- a/templates/rest/checkout_orders/RefundCapturedPayment.php
+++ /dev/null
@@ -1,41 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$capture_id = '';           // The PayPal-generated ID for the captured payment to refund.
-
-$amount = array(            // The amount to refund.
-    'currency_code' => '',
-    'value' => '',
-);
-
-$invoice_id = '';           // Maximum length: 127. The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
-$note_to_payer = '';        // Maximum length: 255. The reason for the refund. Appears in both the payer's transaction history and the emails that the payer receives.
-
-$requestArray = array(
-
-    'amount' => $amount,
-    'note_to_payer' => $note_to_payer,
-    'invoice_id' => $invoice_id,
-);
-
-$response = $PayPal->RefundCapturedPayment($capture_id,$requestArray);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/ShowRefundDetails.php b/templates/rest/checkout_orders/ShowRefundDetails.php
deleted file mode 100644
index 303fbb28..00000000
--- a/templates/rest/checkout_orders/ShowRefundDetails.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$refund_id = '';       // The PayPal-generated ID for the refund for which to show details.
-
-$response = $PayPal->ShowRefundDetails($refund_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/checkout_orders/VoidAuthorizedPayment.php b/templates/rest/checkout_orders/VoidAuthorizedPayment.php
deleted file mode 100644
index 511250af..00000000
--- a/templates/rest/checkout_orders/VoidAuthorizedPayment.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new CheckoutOrdersAPI($configArray);
-
-$authorization_id  = '';       // The PayPal-generated ID for the authorized payment to void.
-
-$response = $PayPal->VoidAuthorizedPayment($authorization_id);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/AcceptClaim.php b/templates/rest/customer-disputes/AcceptClaim.php
deleted file mode 100644
index 983efc75..00000000
--- a/templates/rest/customer-disputes/AcceptClaim.php
+++ /dev/null
@@ -1,62 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute for which to accept a claim.
-
-
-$address_details = array(
-    'street_number' => '',     // The street number. Maximum length: 300.
-    'street_name' => '',       // The street name. Just Drury in Drury Lane. Maximum length: 300.
-    'street_type' => '',       // The street type. For example, avenue, boulevard, road, or expressway. Maximum length: 300.
-    'delivery_service' => '',  // The delivery service. Post office box, bag number, or post office name. Maximum length: 300.
-    'building_name' => '',     // A named locations that represents the premise. Usually a building name or number or collection of buildings with a common name or number. For example, Craven House.
-    'sub_building' => ''       // The first-order entity below a named building or location that represents the sub-premise. Usually a single building within a collection of buildings with a common name. Can be a flat, story, floor, room, or apartment.
-);
-
-
-$address_portable = array(
-    'address_line_1' => '',   // The first line of the address. For example, number or street. For example, 173 Drury Lane. Required for data entry and compliance and risk checks. Must contain the full address. Maximum length: 300.
-    'address_line_2' => '',   // The second line of the address. For example, suite or apartment number. Maximum length: 300.
-    'address_line_3' => '',   // The third line of the address, if needed. For example, a street complement for Brazil, direction text, such as next to Walmart, or a landmark in an Indian address. Maximum length: 300.
-    'admin_area_4'   => '',   // The neighborhood, ward, or district. Smaller than admin_area_level_3 or sub_locality. Value is: 1) The postal sorting code that is used in Guernsey and many French territories, such as French Guiana. 2) The fine-grained administrative levels in China. Maximum length: 300.
-    'admin_area_3'   => '',   // A sub-locality, suburb, neighborhood, or district. Smaller than admin_area_level_2. Value is: 1) Brazil. Suburb, bairro, or neighborhood. 2)  India. Sub-locality or district. Street name information is not always available but a sub-locality or district can be a very small area. Maximum length: 300.
-    'admin_area_2'   => '',   // A city, town, or village. Smaller than admin_area_level_1. Maximum length: 300.
-    'admin_area_1'   => '',   // The highest level sub-division in a country, which is usually a province, state, or ISO-3166-2 subdivision. Format for postal delivery. For example, CA and not California. Value, by country, is: 1) UK. A county. 2) US. A state. 3) Canada. A province. 4) Japan. A prefecture. 5) Switzerland. A kanton. Maximum length: 300.
-    'postal_code'    => '',   // The postal code, which is the zip code or equivalent. Typically required for countries with a postal code or an equivalent. Maximum length: 60.
-    'country_code'   => '',   // Minimum length: 2. Maximum length: 2. Pattern: ^([A-Z]{2}|C2)$ The two-character ISO 3166-1 code that identifies the country or region.
-    'address_details'=> array_filter($address_details)
-);
-
-$amount = array(
-    'currency_code' => '',
-    'value' => ''
-);
-        
-
-$parameters = array(
-    'note' => 'Refund to the customer.',     // The merchant's notes about the claim. PayPal can, but the customer cannot, view these notes. Minimum length: 1. Maximum length: 2000.
-    'accept_claim_reason' => '',             // DID_NOT_SHIP_ITEM | TOO_TIME_CONSUMING | LOST_IN_MAIL | NOT_ABLE_TO_WIN | COMPANY_POLICY | REASON_NOT_SET | The merchant's reason for acceptance of the customer's claim.
-    'invoice_id' => '',                      // The merchant-provided ID of the invoice for the refund. This optional value is used to map the refund to an invoice ID in the merchant's system.
-    'return_shipping_address' => array_filter($address_portable),     // Required when the customer must return an item to the merchant for the MERCHANDISE_OR_SERVICE_NOT_AS_DESCRIBED dispute reason, especially if the refund amount is less than the dispute amount.
-    'refund_amount' => array_filter($amount)               // To accept a customer's claim, the amount that the merchant agrees to refund the customer. The subsequent action depends on the amount: 1) If this amount is less than the customer-requested amount, the dispute updates to require customer acceptance. 2) If this amount is equal to or greater than the customer-requested amount, this amount is automatically refunded to the customer and the dispute closes.
-
-);
-
-$response = $PayPal->AcceptClaim($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/DisputesAppeal.php b/templates/rest/customer-disputes/DisputesAppeal.php
deleted file mode 100644
index 5a25aa02..00000000
--- a/templates/rest/customer-disputes/DisputesAppeal.php
+++ /dev/null
@@ -1,81 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';                      // The ID of the dispute for which to accept a claim.
-
-
-//  carrier_name enum The name of the carrier for the shipment of the transaction for this dispute. The possible values are:
-// | UPS | USPS | FEDEX | AIRBORNE_EXPRESS | DHL | AIRSURE | ROYAL_MAIL | PARCELFORCE | SWIFTAIR | OTHER | UK_PARCELFORCE 
-// | UK_ROYALMAIL_SPECIAL UK_ROYALMAIL_RECORDED | UK_ROYALMAIL_INT_SIGNED | UK_ROYALMAIL_AIRSURE | UK_UPS | UK_FEDEX 
-// | UK_AIRBORNE_EXPRESS | UK_DHL UK_OTHER | UK_CANNOT_PROV_TRACK | CA_CANADA_POST | CA_PUROLATOR | CA_CANPAR | CA_LOOMIS  
-// | CA_TNT | CA_OTHER | CA_CANNOT_PROV_TRACK DE_DP_DHL_WITHIN_EUROPE | DE_DP_DHL_T_AND_T_EXPRESS | DE_DHL_DP_INTL_SHIPMENTS | DE_GLS | DE_DPD_DELISTACK | DE_HERMES
-// | DE_UPS | DE_FEDEX | DE_TNT | DE_OTHER | FR_CHRONOPOST | FR_COLIPOSTE | FR_DHL | FR_UPS | FR_FEDEX | FR_TNT | FR_GLS | FR_OTHER
-// | IT_POSTE_ITALIA | IT_DHL | IT_UPS | IT_FEDEX | IT_TNT | IT_GLS | IT_OTHER | AU_AUSTRALIA_POST_EP_PLAT | AU_AUSTRALIA_POST_EPARCEL | | | AU_AUSTRALIA_POST_EMS AU_DHL 
-// | AU_STAR_TRACK_EXPRESS | AU_UPS | AU_FEDEX | AU_TNT | AU_TOLL_IPEC | AU_OTHER | FR_SUIVI | IT_EBOOST_SDA
-// | ES_CORREOS_DE_ESPANA | ES_DHL | ES_UPS | ES_FEDEX | ES_TNT | ES_OTHER | AT_AUSTRIAN_POST_EMS | AT_AUSTRIAN_POST_PPRIME | BE_CHRONOPOST | 
-// | BE_TAXIPOST CH_SWISS_POST_EXPRES | CH_SWISS_POST_PRIORITY | CN_CHINA_POST | HK_HONGKONG_POST | IE_AN_POST_SDS_EMS
-// | IE_AN_POST_SDS_PRIORITY | IE_AN_POST_REGISTERED | IE_AN_POST_SWIFTPOST | IN_INDIAPOST | JP_JAPANPOST | KR_KOREA_POST | NL_TPG | | SG_SINGPOST
-// | TW_CHUNGHWA_POST | CN_CHINA_POST_EMS | CN_FEDEX | CN_TNT | CN_UPS | CN_OTHER | NL_TNT | NL_DHL | NL_UPS | NL_FEDEX | NL_KIALA | BE_KIALA 
-// | PL_POCZTA_POLSKA PL_POCZTEX | PL_GLS | PL_MASTERLINK | PL_TNT | PL_DHL | PL_UPS | PL_FEDEX | JP_SAGAWA_KYUU_BIN | JP_NITTSU_PELICAN_BIN | JP_KURO_NEKO_YAMATO_UNYUU 
-// | JP_TNT | JP_DHL | JP_UPS | JP_FEDEX | NL_PICKUP | NL_INTANGIBLE | NL_ABC_MAIL | HK_FOUR_PX_EXPRESS | HK_FLYT_EXPRESS
-
-
-$tracking_info = array(
-    'carrier_name' => '',               // The name of the carrier for the shipment of the transaction for this dispute.
-    'carrier_name_other' => '',         // This field capture the name of carrier in free form text for unavailable carriers from existing list.
-    'tracking_url' => '',               // The URL to track the dispute-related transaction shipment.
-    'tracking_number' => ''             // The number to track the dispute-related transaction shipment.
-);
-
-$refund_ids =array(
-    'refund_id' => ''                   // The ID of the refunded transaction.
-);
-
-$evidence_info = array(
-    'tracking_info' => $tracking_info,  // An array of relevant tracking information for the transaction involved in this dispute.
-    'refund_ids' => $refund_ids         // An array of refund IDs for the transaction involved in this dispute.    
-);
-
-$documents = array(
-    'name' => '',                       // The document name.
-    'size' => ''                        // The document size.
-);
-
-
-$evidences = array(
-    'evidence_type' => '',                      // PROOF_OF_FULFILLMENT | PROOF_OF_REFUND | PROOF_OF_DELIVERY_SIGNATURE | PROOF_OF_RECEIPT_COPY | RETURN_POLICY | BILLING_AGREEMENT | PROOF_OF_RESHIPMENT | ITEM_DESCRIPTION | POLICE_REPORT | AFFIDAVIT | PAID_WITH_OTHER_METHOD | COPY_OF_CONTRACT | TERMINAL_ATM_RECEIPT | PRICE_DIFFERENCE_REASON | SOURCE_CONVERSION_RATE | BANK_STATEMENT | CREDIT_DUE_REASON | REQUEST_CREDIT_RECEIPT | PROOF_OF_RETURN | CREATE | CHANGE_REASON | OTHER
-    'evidence_info' => $evidence_info,          // The evidence-related information.
-    'documents' => $documents,                  // An array of evidence documents.
-    'notes' => '',                              // Any evidence-related notes. Maximum length: 2000.
-    'item_id' => ''                             // The item ID. If the merchant provides multiple pieces of evidence and the transaction has multiple item IDs, the merchant can use this value to associate a piece of evidence with an item ID.    
-);
-
-$parameters = array(
-    'evidences' => $evidences,                  // An array of evidences for the dispute.
-);
-
-$response = $PayPal->DisputesAppeal($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/DisputesEscalate.php b/templates/rest/customer-disputes/DisputesEscalate.php
deleted file mode 100644
index 7e104415..00000000
--- a/templates/rest/customer-disputes/DisputesEscalate.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';                                              // The ID of the dispute to escalate to a claim.
-
-$parameters = array(
-    'note' => '',                                               // The merchant's notes about the claim. PayPal can, but the customer cannot, view these notes. Minimum length: 1. Maximum length: 2000.   
-);
-
-$response = $PayPal->DisputesEscalate($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/DisputesMakeOffer.php b/templates/rest/customer-disputes/DisputesMakeOffer.php
deleted file mode 100644
index 52eed2f3..00000000
--- a/templates/rest/customer-disputes/DisputesMakeOffer.php
+++ /dev/null
@@ -1,56 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute for which to make an offer.
-
-$offer_amount = array(
-    'currency_code' => '',
-    'value' => ''
-);
-$address_details = array(
-    'street_number' => '',     // The street number. Maximum length: 300.
-    'street_name' => '',       // The street name. Just Drury in Drury Lane. Maximum length: 300.
-    'street_type' => '',       // The street type. For example, avenue, boulevard, road, or expressway. Maximum length: 300.
-    'delivery_service' => '',  // The delivery service. Post office box, bag number, or post office name. Maximum length: 300.
-    'building_name' => '',     // A named locations that represents the premise. Usually a building name or number or collection of buildings with a common name or number. For example, Craven House.
-    'sub_building' => ''       // The first-order entity below a named building or location that represents the sub-premise. Usually a single building within a collection of buildings with a common name. Can be a flat, story, floor, room, or apartment.
-);
-$return_shipping_address = array(
-    'address_line_1' => '',   // The first line of the address. For example, number or street. For example, 173 Drury Lane. Required for data entry and compliance and risk checks. Must contain the full address. Maximum length: 300.
-    'address_line_2' => '',   // The second line of the address. For example, suite or apartment number. Maximum length: 300.
-    'address_line_3' => '',   // The third line of the address, if needed. For example, a street complement for Brazil, direction text, such as next to Walmart, or a landmark in an Indian address. Maximum length: 300.
-    'admin_area_4'   => '',   // The neighborhood, ward, or district. Smaller than admin_area_level_3 or sub_locality. Value is: 1) The postal sorting code that is used in Guernsey and many French territories, such as French Guiana. 2) The fine-grained administrative levels in China. Maximum length: 300.
-    'admin_area_3'   => '',   // A sub-locality, suburb, neighborhood, or district. Smaller than admin_area_level_2. Value is: 1) Brazil. Suburb, bairro, or neighborhood. 2)  India. Sub-locality or district. Street name information is not always available but a sub-locality or district can be a very small area. Maximum length: 300.
-    'admin_area_2'   => '',   // A city, town, or village. Smaller than admin_area_level_1. Maximum length: 300.
-    'admin_area_1'   => '',   // The highest level sub-division in a country, which is usually a province, state, or ISO-3166-2 subdivision. Format for postal delivery. For example, CA and not California. Value, by country, is: 1) UK. A county. 2) US. A state. 3) Canada. A province. 4) Japan. A prefecture. 5) Switzerland. A kanton. Maximum length: 300.
-    'postal_code'    => '',   // The postal code, which is the zip code or equivalent. Typically required for countries with a postal code or an equivalent. Maximum length: 60.
-    'country_code'   => '',   // Minimum length: 2. Maximum length: 2. Pattern: ^([A-Z]{2}|C2)$ The two-character ISO 3166-1 code that identifies the country or region.
-    'address_details'=> array_filter($address_details)
-);
-
-$parameters = array(
-    'note' => '',                                                       // The merchant's notes about the claim. PayPal can, but the customer cannot, view these notes. Minimum length: 1. Maximum length: 2000.   
-    'offer_amount' => array_filter($offer_amount),                      // The amount proposed to resolve the dispute.
-    'offer_type' => '',                                                 // The type of offer that the merchant proposes for the dispute. The allowed values are: REFUND | REFUND_WITH_RETURN | REFUND_WITH_REPLACEMENT
-    'invoice_id' => '',                                                 // The merchant-provided ID of the invoice for the refund. This optional value maps the refund to an invoice ID in the merchant's system.
-    'return_shipping_address' => array_filter($return_shipping_address) // The return address for the item. Required when the customer must return an item to the merchant for the MERCHANDISE_OR_SERVICE_NOT_AS_DESCRIBED dispute reason, especially if the refund amount is less than the dispute amount.
-);
-
-$response = $PayPal->DisputesMakeOffer($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/ListDisputes.php b/templates/rest/customer-disputes/ListDisputes.php
deleted file mode 100644
index 9fb956a8..00000000
--- a/templates/rest/customer-disputes/ListDisputes.php
+++ /dev/null
@@ -1,34 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-/**
- *  Note for parameter : You can specify either but not both 
- *  the start_time and disputed_transaction_id query parameter. 
- *  If you omit the start time, default is the current date and time.
- */
-
-$parameters = array(
-    'disputed_transaction_id' => '',                  // Filters the disputes in the response by a transaction, by ID. You can specify either but not both the start_time and disputed_transaction_id query parameter.
-    //'start_time' => '',                             // Format yyyy-MM-ddTHH:mm:ss.SSSZ. For example 2018-10-03T09:53:06.000Z, Filters the disputes in the response by a creation date and time. The start time must be within the last 180 days. 
-    'page_size' => '',                                // Default: 10. Minimum value: 1. Maximum value: 50. Limits the number of disputes in the response to this value.
-    'next_page_token' => '',                          // The token that describes the next page of results to fetch. The list disputes call returns this token in the HATEOAS links in the response. If you omit this parameter, the API returns the first page of data.
-    'dispute_state' => ''                             // REQUIRED_ACTION | REQUIRED_OTHER_PARTY_ACTION | UNDER_PAYPAL_REVIEW | RESOLVED | OPEN_INQUIRIES | Filters the disputes in the response by a state.   
-);
-$response = $PayPal->ListDisputes($parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/templates/rest/customer-disputes/ProvideEvidence.php b/templates/rest/customer-disputes/ProvideEvidence.php
deleted file mode 100644
index 11d0603e..00000000
--- a/templates/rest/customer-disputes/ProvideEvidence.php
+++ /dev/null
@@ -1,85 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute for which to accept a claim.
-
-
-//  carrier_name enum The name of the carrier for the shipment of the transaction for this dispute. The possible values are:
-// | UPS | USPS | FEDEX | AIRBORNE_EXPRESS | DHL     | AIRSURE | ROYAL_MAIL | PARCELFORCE | SWIFTAIR | OTHER | UK_PARCELFORCE 
-// | UK_ROYALMAIL_SPECIAL UK_ROYALMAIL_RECORDED | UK_ROYALMAIL_INT_SIGNED | UK_ROYALMAIL_AIRSURE | UK_UPS | UK_FEDEX 
-// | UK_AIRBORNE_EXPRESS | UK_DHL UK_OTHER | UK_CANNOT_PROV_TRACK | CA_CANADA_POST | CA_PUROLATOR | CA_CANPAR | CA_LOOMIS  
-// | CA_TNT | CA_OTHER | CA_CANNOT_PROV_TRACK DE_DP_DHL_WITHIN_EUROPE | DE_DP_DHL_T_AND_T_EXPRESS | DE_DHL_DP_INTL_SHIPMENTS | DE_GLS | DE_DPD_DELISTACK | DE_HERMES
-// | DE_UPS | DE_FEDEX | DE_TNT | DE_OTHER | FR_CHRONOPOST | FR_COLIPOSTE | FR_DHL | FR_UPS | FR_FEDEX | FR_TNT | FR_GLS | FR_OTHER
-// | IT_POSTE_ITALIA | IT_DHL | IT_UPS | IT_FEDEX | IT_TNT | IT_GLS | IT_OTHER | AU_AUSTRALIA_POST_EP_PLAT | AU_AUSTRALIA_POST_EPARCEL | | | AU_AUSTRALIA_POST_EMS AU_DHL 
-// | AU_STAR_TRACK_EXPRESS | AU_UPS | AU_FEDEX | AU_TNT | AU_TOLL_IPEC | AU_OTHER | FR_SUIVI | IT_EBOOST_SDA
-// | ES_CORREOS_DE_ESPANA | ES_DHL | ES_UPS | ES_FEDEX | ES_TNT | ES_OTHER | AT_AUSTRIAN_POST_EMS | AT_AUSTRIAN_POST_PPRIME | BE_CHRONOPOST | 
-// | BE_TAXIPOST CH_SWISS_POST_EXPRES | CH_SWISS_POST_PRIORITY | CN_CHINA_POST | HK_HONGKONG_POST | IE_AN_POST_SDS_EMS
-// | IE_AN_POST_SDS_PRIORITY | IE_AN_POST_REGISTERED | IE_AN_POST_SWIFTPOST | IN_INDIAPOST | JP_JAPANPOST | KR_KOREA_POST | NL_TPG | | SG_SINGPOST
-// | TW_CHUNGHWA_POST | CN_CHINA_POST_EMS | CN_FEDEX | CN_TNT | CN_UPS | CN_OTHER | NL_TNT | NL_DHL | NL_UPS | NL_FEDEX | NL_KIALA | BE_KIALA 
-// | PL_POCZTA_POLSKA PL_POCZTEX | PL_GLS | PL_MASTERLINK | PL_TNT | PL_DHL | PL_UPS | PL_FEDEX | JP_SAGAWA_KYUU_BIN | JP_NITTSU_PELICAN_BIN | JP_KURO_NEKO_YAMATO_UNYUU 
-// | JP_TNT | JP_DHL | JP_UPS | JP_FEDEX | NL_PICKUP | NL_INTANGIBLE | NL_ABC_MAIL | HK_FOUR_PX_EXPRESS | HK_FLYT_EXPRESS
-
-
-$tracking_info = array(
-    'carrier_name' => '',                       // The name of the carrier for the shipment of the transaction for this dispute.
-    'carrier_name_other' => '',                 // This field capture the name of carrier in free form text for unavailable carriers from existing list.
-    'tracking_url' => '',                       // The URL to track the dispute-related transaction shipment.
-    'tracking_number' => ''                     // The number to track the dispute-related transaction shipment.
-);
-
-$refund_ids =array(
-    'refund_id' => ''                           // The ID of the refunded transaction.
-);
-
-$evidence_info = array(
-    'tracking_info' => $tracking_info,          // An array of relevant tracking information for the transaction involved in this dispute.
-    'refund_ids' => $refund_ids                 // An array of refund IDs for the transaction involved in this dispute.    
-);
-
-$documents = array(
-    'name' => '',                               // The document name.
-    'size' => ''                                // The document size.
-);
-
-$evidences = array(
-    'evidence_type' => '',                      // PROOF_OF_FULFILLMENT | PROOF_OF_REFUND | PROOF_OF_DELIVERY_SIGNATURE | PROOF_OF_RECEIPT_COPY | RETURN_POLICY | BILLING_AGREEMENT | PROOF_OF_RESHIPMENT | ITEM_DESCRIPTION | POLICE_REPORT | AFFIDAVIT | PAID_WITH_OTHER_METHOD | COPY_OF_CONTRACT | TERMINAL_ATM_RECEIPT | PRICE_DIFFERENCE_REASON | SOURCE_CONVERSION_RATE | BANK_STATEMENT | CREDIT_DUE_REASON | REQUEST_CREDIT_RECEIPT | PROOF_OF_RETURN | CREATE | CHANGE_REASON | OTHER
-    'evidence_info' => $evidence_info,          // The evidence-related information.
-    'documents' => $documents,                  // An array of evidence documents.
-    'notes' => '',                              // Any evidence-related notes. Maximum length: 2000.
-    'item_id' => ''                             // The item ID. If the merchant provides multiple pieces of evidence and the transaction has multiple item IDs, the merchant can use this value to associate a piece of evidence with an item ID.
-);
-
-$parameters = array(
-    'evidences' => $evidences,                  // An array of evidences for the dispute.
-);
-
-$response = $PayPal->ProvideEvidence($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/SendMessageToOtherParty.php b/templates/rest/customer-disputes/SendMessageToOtherParty.php
deleted file mode 100644
index aa496d85..00000000
--- a/templates/rest/customer-disputes/SendMessageToOtherParty.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute for which to send a message.
-
-$parameters = array(
-    'message' => '',   // The message sent by the merchant to the other party.
-);
-
-$response = $PayPal->SendMessageToOtherParty($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/templates/rest/customer-disputes/SettleDispute.php b/templates/rest/customer-disputes/SettleDispute.php
deleted file mode 100644
index f829a7b1..00000000
--- a/templates/rest/customer-disputes/SettleDispute.php
+++ /dev/null
@@ -1,35 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute for which to accept a claim.
-
-// The outcome of the adjudication. The allowed values are:
-// SELLER_FAVOR. This will resolve the case in seller favor and outcome will be set as RESOLVED_SELLER_FAVOR
-// BUYER_FAVOR. This will resolve the case in buyer favor and outcome will be set as RESOLVED_BUYER_FAVOR
-
-$parameters = array(
-    'adjudication_outcome' => '',   // The allowed values are: BUYER_FAVOR and SELLER_FAVOR The outcome of the adjudication. 
-);
-
-$response = $PayPal->SettleDispute($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/customer-disputes/ShowDisputeDetails.php b/templates/rest/customer-disputes/ShowDisputeDetails.php
deleted file mode 100644
index 6e432152..00000000
--- a/templates/rest/customer-disputes/ShowDisputeDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute for which to show details.
-
-$response = $PayPal->ShowDisputeDetails($dispute_id);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/templates/rest/customer-disputes/UpdateDisputeStatus.php b/templates/rest/customer-disputes/UpdateDisputeStatus.php
deleted file mode 100644
index 1f03d2d8..00000000
--- a/templates/rest/customer-disputes/UpdateDisputeStatus.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\customerdisputes\CustomerDisputesAPI($configArray);
-
-$dispute_id  = '';   // The ID of the dispute that requires evidence.
-
-/**
- *      If action is BUYER_EVIDENCE The status updates to WAITING_FOR_BUYER_RESPONSE      
- *      If action is SELLER_EVIDENCE The status updates to WAITING_FOR_SELLER_RESPONSE 
- *  */
-
-$parameters = array(
-    'action' => '',   // The action. Indicates whether the state change enables the customer or merchant to submit evidence:
-);
-
-$response = $PayPal->UpdateDisputeStatus($dispute_id,$parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/templates/rest/identity/GetUserConsentURL.php b/templates/rest/identity/GetUserConsentURL.php
deleted file mode 100644
index 63eb70d5..00000000
--- a/templates/rest/identity/GetUserConsentURL.php
+++ /dev/null
@@ -1,37 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\identity\IdentityAPI($configArray);
-
-$redirectUri = '';  // Uri on merchant website to where the user must be redirected to post paypal login
-
-// @param array $scope The access privilges that you are requesting for from the user. Pass empty array for all scopes.
-$Scope   = array(); 
-
-$requestData = array(
-    'redirectUri' => $redirectUri,
-    'scope'       => $Scope,
-);
-        
-$returnArray = $PayPal->GetUserConsentURL($requestData);
-echo "
";
-print_r($returnArray);
-echo "
"; -if($sandbox){ -echo 'Click Here to Obtain User Consent'; -} -else{ - echo 'Click Here to Obtain User Consent'; -} -?> \ No newline at end of file diff --git a/templates/rest/identity/GetUserInfo.php b/templates/rest/identity/GetUserInfo.php deleted file mode 100644 index 63c6d793..00000000 --- a/templates/rest/identity/GetUserInfo.php +++ /dev/null @@ -1,34 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new \angelleye\PayPal\rest\identity\IdentityAPI($configArray); -// To obtain User Info, you have to follow three steps in general. -// First, you need to obtain user's consent to retrieve the information you want. -// This is explained in the example "GetUserConsentURL.php". - -// Once you get the user's consent, the end result would be long lived refresh token. -// This refresh token should be stored in a permanent storage for later use. - -// You can retrieve the refresh token by executing GetUserConsentURL.php and store the refresh token - -$refreshToken= ''; - -$requestData = array( - 'refreshToken' => $refreshToken, -); - -$returnArray = $PayPal->GetUserInfo($requestData); -echo "
";
-print_r($returnArray);
-echo "
"; \ No newline at end of file diff --git a/templates/rest/identity/UserConsentRedirect.php b/templates/rest/identity/UserConsentRedirect.php deleted file mode 100644 index 4fd1b666..00000000 --- a/templates/rest/identity/UserConsentRedirect.php +++ /dev/null @@ -1,29 +0,0 @@ - $sandbox, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - 'LogLevel' => $log_level -); - -$PayPal = new \angelleye\PayPal\rest\identity\IdentityAPI($configArray); - -// ### User Consent Response -// PayPal would redirect the user to the redirect_uri mentioned when creating the consent URL. -// The user would then able to retrieve the access token by getting the code, which is returned as a GET parameter. - -if (isset($_GET['success']) && $_GET['success'] == 'true') { - $code = isset($_GET['code']) ? $_GET['code'] : ''; - $returnArray = $PayPal->GetUserConsentRedirect($code); - echo "
";
-    print_r($returnArray);
-}
-else{
-    echo "Something went wrong.";
-}
\ No newline at end of file
diff --git a/templates/rest/invoice-templates/CreateInvoiceTemplate.php b/templates/rest/invoice-templates/CreateInvoiceTemplate.php
deleted file mode 100755
index 15624dc8..00000000
--- a/templates/rest/invoice-templates/CreateInvoiceTemplate.php
+++ /dev/null
@@ -1,183 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-$InvoiceItemArray = array();
-
-$InvoiceItem = array(
-        'Name'          => '',                                    // Name of the item. 200 characters max.
-        'Description'   => '',                             // Description of the item. 1000 characters max.
-        'Quantity'      => '',                                // Quantity of the item. Range of -10000 to 10000.
-        'Date'          => '',                                // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6). 
-        'Discount'      => array(
-                                'Percent' => ''              // Cost in percent. Range of 0 to 100.
-                            ),
-        'UnitOfMeasure' => '',                               // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"]. The unit of measure of the item being invoiced.        
-        'UnitPrice'     => array(
-                                'Currency' => '',                       // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),                                 // Unit price of the item. Range of -1,000,000 to 1,000,000.
-        'Tax'           => array(
-                                'Name'    => '',
-                                'Percent' => '',    
-                            )                           
-);
-
-array_push($InvoiceItemArray, $InvoiceItem);
-
-$merchantInfo = array(
-    'Email' => '',                                           // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => '',                                       // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => '',                                       // The merchant last name. Maximum length is 30 characters.        
-    'BusinessName' => '',                                    // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => '',                                            // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                        // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                        // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => '',                                     // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                         // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => '',                                   // Additional information, such as business hours. Maximum length is 40 characters.    
-    'NotificationChannel' => '',                              // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-
-$shippingInfo = array(
-    'FirstName' => '',                                      // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => '',                                      // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => '',                                   // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$templateDataCcInfo =  '';                                      // For invoices sent by email, one or more email addresses to which to send a Cc: copy of the notification. Supports only email addresses under participant.
-
-$templateData = array(    
-    'Reference'  => '',                                  // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.    
-    'AllowPartialPayment' => '',                         // Indicates whether the invoice allows a partial payment. If set to `false`, invoice must be paid in full. If set to `true`, the invoice allows partial payments. Default is `false`.   
-    'MinimumAmountDue' => array(
-                                'Currency' => '',                       // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),    
-    'TaxCalculatedAfterDiscount'    => '',              // Indicates whether tax is calculated before or after a discount. If set to `false`, the tax is calculated before a discount. If set to `true`, the tax is calculated after a discount. Default is `false`.
-    'TaxInclusive' => '',                               // Default is `false`. Indicates whether the unit price includes tax. 
-    'Note'  => '',                                      // Note to the payer. 4000 characters max.
-    'MerchantMemo'  => '',                              // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'   => '',                                  // Full URL of an external image to use as the logo. Maximum length is 4000 characters.
-    'TotalAmount' => array(
-                                'Currency' => '',                       // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''                        // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                     ),                                    
-);
-$templateDiscount = array(
-    'Percent' => '',                                    // The invoice level discount, as a percent or an amount value.
-);
-
-
-
-$paymentTerm = array(
-    'TermType' => '',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                          // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-$attachments = array(
-    'Name' => '',                                           // Name of the file attached. 
-    'Url'  => '' // URL of the attached file that can be downloaded.                                             // URL of the attached file that can be downloaded. 
-);
-
-
-$TemplateSettingsMetadata = array(
-    'Hidden' => ''                                          // Indicates whether this field should be hidden. default is false
-);
-
-$TemplateSettings = array(
-    'FieldName'         => '' ,                          // The field name (for any field in template_data) for which the corresponding display preferences will be mapped to.    
-);
-
-$Template = array(
-    'TemplateId'    => '',                                  // Unique identifier id of the template.    
-    'Name'          => '',                                  // Name of the template.
-    'Default'       => '',                                  // Indicates that this template is merchant's default. There can be only one template which can be a default.
-    'UnitOfMeasure' => '',                                  // Unit of measure for the template, possible values are Quantity, Hours, Amount.
-    'Custom'        => '',                                  // Indicates whether this is a custom template created by the merchant. Non custom templates are system generated    
-);
-
-$requestData = array(
-    'InvoiceItemArray' => $InvoiceItemArray,
-    'merchantInfo'     => $merchantInfo,
-    'merchantPhone'    => $merchantPhone,
-    'merchantAddress'  => $merchantAddress,
-    'billingInfo'      => $billingInfo,
-    'billingInfoPhone' => $billingInfoPhone,
-    'billingInfoAddress' => $billingInfoAddress,
-    'shippingInfo'     => $shippingInfo,
-    'shippingInfoPhone' => $shippingInfoPhone,
-    'shippingInfoAddress' => $shippingInfoAddress,
-    'templateData'      => $templateData,
-    'templateDiscount' => $templateDiscount,
-    'paymentTerm'      => $paymentTerm,
-    'attachments'      => $attachments,
-    'TemplateSettingsMetadata' => $TemplateSettingsMetadata,
-    'TemplateSettings' => $TemplateSettings,
-    'Template'         => $Template,
-    'TemplateDataCcInfo' => $templateDataCcInfo
-);
-
-$returnArray = $PayPal->CreateInvoiceTemplate($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice-templates/DeleteInvoiceTemplate.php b/templates/rest/invoice-templates/DeleteInvoiceTemplate.php
deleted file mode 100755
index 8f65ab79..00000000
--- a/templates/rest/invoice-templates/DeleteInvoiceTemplate.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$template_id = '';    // Required.  The ID of the template to delete.
-
-$returnArray = $PayPal->DeleteInvoiceTemplate($template_id);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice-templates/GetAllInvoiceTemplates.php b/templates/rest/invoice-templates/GetAllInvoiceTemplates.php
deleted file mode 100755
index 5ed83b6e..00000000
--- a/templates/rest/invoice-templates/GetAllInvoiceTemplates.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$fields= array(
-    "fields" => ""       // Default: all. The fields to return in the response. Value is all or none. Specify none to return only the template name, ID, and default attributes.
-    );
-
-$returnArray = $PayPal->GetAllInvoiceTemplates($fields);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice-templates/GetInvoiceTemplate.php b/templates/rest/invoice-templates/GetInvoiceTemplate.php
deleted file mode 100755
index 1ee790c2..00000000
--- a/templates/rest/invoice-templates/GetInvoiceTemplate.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$templateId = '';    // Required. The ID of the invoice template for which to show details.
-
-$returnArray = $PayPal->GetInvoiceTemplate($templateId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice-templates/UpdateInvoiceTemplate.php b/templates/rest/invoice-templates/UpdateInvoiceTemplate.php
deleted file mode 100755
index 0d463590..00000000
--- a/templates/rest/invoice-templates/UpdateInvoiceTemplate.php
+++ /dev/null
@@ -1,185 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$template_id = '';                                           // Required. The ID of the template to update.
-
-$InvoiceItemArray = array();
-
-$InvoiceItem = array(
-        'Name'          => '',                               // Name of the item. 200 characters max.
-        'Description'   => '',                               // Description of the item. 1000 characters max.
-        'Quantity'      => '',                               // Quantity of the item. Range of -10000 to 10000.
-        'Date'          => '',                               // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6). 
-        'Discount'      => array(
-                                'Percent' => ''              // Cost in percent. Range of 0 to 100.
-                            ),
-        'UnitOfMeasure' => '',                               // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"]. The unit of measure of the item being invoiced.        
-        'UnitPrice'     => array(
-                                'Currency' => '',            // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''             // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),                               // Unit price of the item. Range of -1,000,000 to 1,000,000.
-        'Tax'           => array(
-                                'Name'    => '',
-                                'Percent' => '',    
-                            )                           
-);
-
-array_push($InvoiceItemArray, $InvoiceItem);
-
-$merchantInfo = array(
-    'Email' => '',                                           // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => '',                                       // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => '',                                       // The merchant last name. Maximum length is 30 characters.        
-    'BusinessName' => '',                                    // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => '',                                            // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                        // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                        // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => '',                                     // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                         // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => '',                                   // Additional information, such as business hours. Maximum length is 40 characters.    
-    'NotificationChannel' => '',                              // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '',                                      // Country code (from in E.164 format).
-    'NationalNumber' => '',                                   // In-country phone number (from in E.164 format).
-    'Extension' => '',                                        // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-
-$shippingInfo = array(
-    'FirstName' => '',                                        // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => '',                                        // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => '',                                     // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '',                                      // Country code (from in E.164 format).
-    'NationalNumber' => '',                                   // In-country phone number (from in E.164 format).
-    'Extension' => '',                                        // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$templateDataCcInfo =  '';                                    // For invoices sent by email, one or more email addresses to which to send a Cc: copy of the notification. Supports only email addresses under participant.
-
-$templateData = array(    
-    'Reference'  => '',                                       // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.    
-    'AllowPartialPayment' => '',                              // Indicates whether the invoice allows a partial payment. If set to `false`, invoice must be paid in full. If set to `true`, the invoice allows partial payments. Default is `false`.   
-    'MinimumAmountDue' => array(
-                                'Currency' => '',             // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''              // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                            ),    
-    'TaxCalculatedAfterDiscount'    => '',                    // Indicates whether tax is calculated before or after a discount. If set to `false`, the tax is calculated before a discount. If set to `true`, the tax is calculated after a discount. Default is `false`.
-    'TaxInclusive' => '',                                     // Default is `false`. Indicates whether the unit price includes tax. 
-    'Note'  => '',                                            // Note to the payer. 4000 characters max.
-    'MerchantMemo'  => '',                                    // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'   => '',                                        // Full URL of an external image to use as the logo. Maximum length is 4000 characters.
-    'TotalAmount' => array(
-                                'Currency' => '',             // 3 letter currency code as defined by ISO 4217.
-                                'Value'    => ''              // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code.
-                     ),                                    
-);
-$templateDiscount = array(
-    'Percent' => '',                                          // The invoice level discount, as a percent or an amount value.
-);
-
-
-
-$paymentTerm = array(
-    'TermType' => '',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                          // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-$attachments = array(
-    'Name' => '',                                             // Name of the file attached. 
-    'Url'  => ''                                              // URL of the attached file that can be downloaded.                                             // URL of the attached file that can be downloaded. 
-);
-
-
-$TemplateSettingsMetadata = array(
-    'Hidden' => ''                                            // Indicates whether this field should be hidden. default is false
-);
-
-$TemplateSettings = array(
-    'FieldName'         => '' ,                               // The field name (for any field in template_data) for which the corresponding display preferences will be mapped to.    
-);
-
-$Template = array(
-    'TemplateId'    => '',                                    // Unique identifier id of the template.    
-    'Name'          => '',                                    // Name of the template.
-    'Default'       => '',                                    // Indicates that this template is merchant's default. There can be only one template which can be a default.
-    'UnitOfMeasure' => '',                                    // Unit of measure for the template, possible values are Quantity, Hours, Amount.
-    'Custom'        => '',                                    // Indicates whether this is a custom template created by the merchant. Non custom templates are system generated    
-);
-
-$requestData = array(
-    'InvoiceItemArray' => $InvoiceItemArray,
-    'merchantInfo'     => $merchantInfo,
-    'merchantPhone'    => $merchantPhone,
-    'merchantAddress'  => $merchantAddress,
-    'billingInfo'      => $billingInfo,
-    'billingInfoPhone' => $billingInfoPhone,
-    'billingInfoAddress' => $billingInfoAddress,
-    'shippingInfo'     => $shippingInfo,
-    'shippingInfoPhone' => $shippingInfoPhone,
-    'shippingInfoAddress' => $shippingInfoAddress,
-    'templateData'      => $templateData,
-    'templateDiscount' => $templateDiscount,
-    'paymentTerm'      => $paymentTerm,
-    'attachments'      => $attachments,
-    'TemplateSettingsMetadata' => $TemplateSettingsMetadata,
-    'TemplateSettings' => $TemplateSettings,
-    'Template'         => $Template,
-    'TemplateDataCcInfo' => $templateDataCcInfo
-);
-
-$returnArray = $PayPal->UpdateInvoiceTemplate($template_id,$requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/CancelInvoice.php b/templates/rest/invoice/CancelInvoice.php
deleted file mode 100755
index 6dfeb69d..00000000
--- a/templates/rest/invoice/CancelInvoice.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$cancelNotification = array(
-    'Subject' => '',                      // Subject of the notification.
-    'Note'    => '',                      // Note to the payer.
-    'SendToMerchant' => '',               // Indicates whether to send a copy of the notification to the merchant.
-    'SendToPayer' => '',                  // Indicates whether to send a copy of the notification to the payer.
-    'CcEmails' => '',                     // Applicable for invoices created with Cc emails. If this field is not in the body, all the cc email addresses added as part of the invoice shall be notified else this field can be used to limit the list of email addresses. Note: additional email addresses are not supported.    
-);
-
-$InvoiceID = '';                          // Required. Specify the ID of the invoice to cancel.
-
-$returnArray = $PayPal->CancelInvoice($cancelNotification,$InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/CreateInvoice.php b/templates/rest/invoice/CreateInvoice.php
deleted file mode 100755
index a68a012e..00000000
--- a/templates/rest/invoice/CreateInvoice.php
+++ /dev/null
@@ -1,168 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-// Merchant informations is Required for creating new Invoice. 
-$merchantInfo = array(
-    'Email' => '',                                           // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => '',                                       // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => '',                                       // The merchant last name. Maximum length is 30 characters.        
-    'BusinessName' => '',                                    // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => '',                                            // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                        // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                        // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => '',                                     // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                         // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => '',                                   // Additional information, such as business hours. Maximum length is 40 characters.    
-    'NotificationChannel' => '',                              // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-  
-$itemArray = array();
-
-$item1 = array(
-    'Name' => '',                                           // Name of the item. 200 characters max.
-    'Description' => '',                                    // Description of the item. 1000 characters max.
-    'Quantity' => '',                                       // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => '',                   // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => ''                    // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. 
-                       ),                                      // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => '',                    // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '',                    // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                        // Tax associated with the item.
-    'Date' => '',                                           // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                         // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                  // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item1);
-
-$item2 = array(
-    'Name' => '',                                           // Name of the item. 200 characters max.
-    'Description' => '',                                    // Description of the item. 1000 characters max.
-    'Quantity' => '',                                       // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => '',                   // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => ''                    // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. 
-                       ),                                      // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => '',                    // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '',                    // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                        // Tax associated with the item.
-    'Date' => '',                                           // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                         // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                  // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item2);
-
-$finalDiscountForInvoice = array(
-    'Percent' => ''                                         // The rate of the specified Discount. Valid range is from 0.001 to 99.999.                         
-);
-
-$shippingInfo = array(
-    'FirstName' => '',                                      // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => '',                                      // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => '',                                   // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$paymentTerm = array(
-    'TermType' => '',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                          // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-$invoiceData = array(
-    'Note' => '',                                             // Note to the payer. 4000 characters max.
-    'Number' => '',                                           // Unique number that appears on the invoice. If left blank will be auto-incremented from the last number. 25 characters max.
-    'TemplateId' => '',                                       // The template ID used for the invoice. Useful for copy functionality.   
-    'Uri' => '',                                              // URI of the invoice resource.
-    'MerchantMemo' => '',                                     // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'      => '',                                     // Full URL of an external image to use as the logo. Maximum length is 4000 characters.    
-);
-
-
-$requestData =array(
-    'merchantInfo'            => $merchantInfo,
-    'merchantPhone'           => $merchantPhone,
-    'merchantAddress'         => $merchantAddress,
-    'billingInfo'             => $billingInfo,
-    'billingInfoPhone'        => $billingInfoPhone,
-    'billingInfoAddress'      => $billingInfoAddress,
-    'itemArray'               => $itemArray,
-    'finalDiscountForInvoice' => $finalDiscountForInvoice,
-    'shippingInfo'            => $shippingInfo,
-    'shippingInfoPhone'       => $shippingInfoPhone,
-    'shippingInfoAddress'     => $shippingInfoAddress,
-    'paymentTerm'             => $paymentTerm,
-    'invoiceData'             => $invoiceData
-);
-
-$returnArray = $PayPal->CreateInvoice($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/CreateThirdPartyInvoice.php b/templates/rest/invoice/CreateThirdPartyInvoice.php
deleted file mode 100644
index b5f92185..00000000
--- a/templates/rest/invoice/CreateThirdPartyInvoice.php
+++ /dev/null
@@ -1,212 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$refreshToken = "";
-
-$thirdPartyMerchant = "";
-
-// Merchant informations is Required for creating new Invoice. 
-$merchantInfo = array(
-    'Email' => $thirdPartyMerchant,                                 // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => '',                                              // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => '',                                              // The merchant last name. Maximum length is 30 characters.        
-    'BusinessName' => '',                                           // The merchant company business name. Maximum length is 100 characters.
-    'Website' => '',                                                // The merchant website. Maximum length is 2048 characters.
-    'TaxId' => '',                                                  // The merchant tax ID. Maximum length is 100 characters. 
-    'AdditionalInfoLabel' => ''                                     // Any additional information, such as business hours. 40 characters max. 
-);
-
-$merchantPhone = array(
-    'CountryCode' => '',                                            // Country code (from in E.164 format).
-    'NationalNumber' => '',                                         // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$merchantFax = array(
-    'CountryCode' => '',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '',                                      // In-country phone number (from in E.164 format).    
-);
-
-$merchantAddress = array(
-    'Line1' => '',                                                  // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                                  // City name.
-    'CountryCode' => '',                                            // 2 letter country code.    
-    'PostalCode'  => '',                                            // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                            // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => '',                                                  // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                              // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                              // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => '',                                           // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                               // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => '',                                         // Additional information, such as business hours. Maximum length is 40 characters.    
-    'NotificationChannel' => '',                                    // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '',                                            // Country code (from in E.164 format).
-    'NationalNumber' => '',                                         // In-country phone number (from in E.164 format).
-    'Extension' => '',                                              // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '',                                                  // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                                  // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                                  // City name.
-    'CountryCode' => '',                                            // 2 letter country code.    
-    'PostalCode'  => '',                                            // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                            // 2 letter code for US states, and the equivalent for other countries.         
-);
-
-$shippingInfo = array(
-    'FirstName' => '',                                          // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => '',                                          // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => '',                                       // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '',                                         // Country code (from in E.164 format).
-    'NationalNumber' => '',                                      // In-country phone number (from in E.164 format).
-    'Extension' => '',                                           // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '',                                              // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                              // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                              // City name.
-    'CountryCode' => '',                                        // 2 letter country code.    
-    'PostalCode'  => '',                                        // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                        // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$CCDetails['Email'] = '';                                           // The participant email address.  
-
-$itemArray = array();
-
-$item1 = array(
-    'Name' => 'Sutures',                                            // Name of the item. 200 characters max.
-    'Description' => '',                                            // Description of the item. 1000 characters max.
-    'Quantity' => '100',                                            // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => '',                           // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => ''                            // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. 
-                       ),                                           // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => '',                            // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '',                            // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                             // Tax associated with the item.
-    'Date' => '',                                                   // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                              // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                          // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item1);
-
-$item2 = array(
-    'Name' => '',                                                   // Name of the item. 200 characters max.
-    'Description' => '',                                            // Description of the item. 1000 characters max.
-    'Quantity' => '',                                               // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => '',                           // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => ''                            // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. 
-                       ),                                           // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => '',                            // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '',                            // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                             // Tax associated with the item.
-    'Date' => '',                                                   // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                              // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                          // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item2);
-
-$paymentTerm = array(
-    'TermType' => '',                                               // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                                // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-/*   Note : For Invoice discount 
- *   we have to add types like percent and Amount 
- *   and based on that discount will be calculated
- *   In Sample code we have added Percent type
- *   To add Amount type use this code
- *   $finalDiscountForInvoice = array(
-        'type' => 'Amount',
-        'Amount' => array (
-                    'Currency' => 'USD',
-                    'Value' => 20.00
-        ));
- * 
- */
-$finalDiscountForInvoice = array(
-        'type' => '', 
-        'Percent' => ''
-    );
-
-$today_date = date('Y-m-d Z', time());  
-$invoiceData = array(
-    'InvoiceDate' => $today_date,                             // The date when the invoice was enabled. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Note' => '',             // Note to the payer. 4000 characters max.
-    'Number' => '',                                           // Unique number that appears on the invoice. If left blank will be auto-incremented from the last number. 25 characters max.
-    'TemplateId' => '',                                       // The template ID used for the invoice. Useful for copy functionality.   
-    'Uri' => '',                                              // URI of the invoice resource.
-    'MerchantMemo' => '',                                     // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'      => '',                                     // Full URL of an external image to use as the logo. Maximum length is 4000 characters.    
-    'Reference' => '',                                        // Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters.  
-    'Terms' => '',    
-    'AllowPartialPayment' => '',    
-);
-
-
-$requestData =array(
-    'merchantInfo'            => $merchantInfo,
-    'merchantPhone'           => $merchantPhone,
-    'merchantFax'             => $merchantFax,
-    'merchantAddress'         => $merchantAddress,
-    'billingInfo'             => $billingInfo,
-    'billingInfoPhone'        => $billingInfoPhone,
-    'billingInfoAddress'      => $billingInfoAddress,
-    'ccInfo'                  => $CCDetails,
-    'itemArray'               => $itemArray,
-    'finalDiscountForInvoice' => $finalDiscountForInvoice,
-    'shippingInfo'            => $shippingInfo,
-    'shippingInfoPhone'       => $shippingInfoPhone,
-    'shippingInfoAddress'     => $shippingInfoAddress,
-    'paymentTerm'             => $paymentTerm,
-    'invoiceData'             => $invoiceData
-);
-
-$returnArray = $PayPal->CreateInvoice($requestData,true,$refreshToken);
-echo "
";
-print_r($returnArray);
-
-
diff --git a/templates/rest/invoice/DeleteInvoice.php b/templates/rest/invoice/DeleteInvoice.php
deleted file mode 100755
index c5ffc45e..00000000
--- a/templates/rest/invoice/DeleteInvoice.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = '';    // Required.  The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->DeleteInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/GetInvoice.php b/templates/rest/invoice/GetInvoice.php
deleted file mode 100755
index e7e49234..00000000
--- a/templates/rest/invoice/GetInvoice.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = '';    // Required. The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->GetInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/GetNextInvoiceNumber.php b/templates/rest/invoice/GetNextInvoiceNumber.php
deleted file mode 100755
index cd4007ef..00000000
--- a/templates/rest/invoice/GetNextInvoiceNumber.php
+++ /dev/null
@@ -1,18 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$returnArray = $PayPal->GetNextInvoiceNumber();
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/GetThirdPartyInvoice.php b/templates/rest/invoice/GetThirdPartyInvoice.php
deleted file mode 100644
index 60c670a5..00000000
--- a/templates/rest/invoice/GetThirdPartyInvoice.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$refreshToken = "";
-
-$invoiceId = '';    //Required. The ID of the invoice for which to show details.
-
-$returnArray = $PayPal->GetThirdPartyInvoice($invoiceId,$refreshToken);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/ListInvoice.php b/templates/rest/invoice/ListInvoice.php
deleted file mode 100755
index 80656a91..00000000
--- a/templates/rest/invoice/ListInvoice.php
+++ /dev/null
@@ -1,24 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$parameters = array(
-    'page'                  => '',                // A zero-relative index of the list of merchant invoices.
-    'page_size'             => '',                // The number of invoices to list beginning with the specified page.
-    'total_count_required ' => '',                // Indicates whether the total count appears in the response. Default is false.
-);
-
-$returnArray = $PayPal->ListInvoice($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/RecordPayment.php b/templates/rest/invoice/RecordPayment.php
deleted file mode 100755
index c08a53cc..00000000
--- a/templates/rest/invoice/RecordPayment.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$record = array(
-    'Method' => '',                          // Valid Values: ["BANK_TRANSFER", "CASH", "CHECK", "CREDIT_CARD", "DEBIT_CARD", "PAYPAL", "WIRE_TRANSFER", "OTHER"].  The payment mode or method. Required with the `EXTERNAL` payment type.
-    'Note'   => '',                          // Optional. A note associated with the payment.
-    'Date'   => '',                          // The date when the invoice was paid. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).    
-);
-
-$amount = array(
-    'currency' => '',                        // The three-letter ISO 4217 alphabetic currency code. 
-    'value'    => ''                         // The amount up to N digits after the decimal separator, as defined in ISO 4217 for the appropriate currency code. 
-);
-
-$invoiceId = '';                             // Required. The ID of the invoice to mark as paid. 
-
-$returnArray = $PayPal->RecordPayment($invoiceId,$record,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/RecordRefund.php b/templates/rest/invoice/RecordRefund.php
deleted file mode 100755
index 3b4edf34..00000000
--- a/templates/rest/invoice/RecordRefund.php
+++ /dev/null
@@ -1,38 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$invoiceId = '';        // Required. Inovoice id for which to record refunds.
-
-$refundDetail = array(
-    'Type' => '',                         // Valid Values: ["PAYPAL", "EXTERNAL"] The PayPal refund type. Indicates whether refund was paid in invoicing flow through PayPal or externally. In the case of mark-as-refunded API, the supported refund type is `EXTERNAL`. For backward compatability, the `PAYPAL` refund type is still supported.
-    'TransactionId' => '',                // The PayPal refund transaction ID. Required with the `PAYPAL` refund type.
-    'Date'   => '',                       // Date on which the invoice was refunded. Date format: yyyy-MM-dd z. For example, 2014-02-27 PST.
-    'Note'   => '',                       // Optional note associated with the refund.    
-);
-
-//Amount to be recorded as refund against invoice. If this field is not passed, the total invoice paid amount is recorded as refund.
-$amount = array(
-    'currency' => '',                                      // The three-letter ISO 4217 alphabetic currency code. 
-    'value'    => ''                                       // The amount up to N digits after the decimal separator, as defined in ISO 4217 for the appropriate currency code. 
-);
-
-$requestData = array(
-    'invoiceId' => $invoiceId,
-    'refundDetail' => $refundDetail,
-    'amount' => $amount
-);
-$returnArray = $PayPal->RecordRefund($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/RemindInvoice.php b/templates/rest/invoice/RemindInvoice.php
deleted file mode 100755
index 0f74e7d1..00000000
--- a/templates/rest/invoice/RemindInvoice.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$remindNotification = array(
-    'Subject' => '',                         // Subject of the notification.
-    'Note'    => '',                         // Note to the payer.
-    'SendToMerchant' => '',                  // Indicates whether to send a copy of the notification to the merchant.
-    'SendToPayer' => '',                     // Indicates whether to send a copy of the notification to the payer.
-    'CcEmails' => '',                        // Applicable for invoices created with Cc emails. If this field is not in the body, all the cc email addresses added as part of the invoice shall be notified else this field can be used to limit the list of email addresses. Note: additional email addresses are not supported.    
-);
-
-$InvoiceID = '';                             // Required. Specify the ID of the invoice to remind.
-
-$returnArray = $PayPal->RemindInvoice($remindNotification,$InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/RetrieveQRCode.php b/templates/rest/invoice/RetrieveQRCode.php
deleted file mode 100755
index 770662f6..00000000
--- a/templates/rest/invoice/RetrieveQRCode.php
+++ /dev/null
@@ -1,30 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$parameters = array(
-    'width'  => '',                              // The width, in pixels, of the QR code image. Valid value is from 150 to 500. Default is 500.Default: 500.
-    'height' => '',                              // The height, in pixels, of the QR code image. Valid value is from 150 to 500. Default is 500.Default: 500.
-    'action' => '',                              // Default: pay. The type of URL for which to generate a QR code. Default is pay and is the only supported value.
-);
-
-$InvoiceID = '';                                // Required. Specify the ID of the invoice to remind.
-
-$path = '';                                     // Path to save Image.
-
-$returnArray = $PayPal->RetrieveQRCode($parameters,$InvoiceID,$path);
-
-echo "
";
-print_r($returnArray);
-echo 'Invoice QR Code';
diff --git a/templates/rest/invoice/SearchInvoices.php b/templates/rest/invoice/SearchInvoices.php
deleted file mode 100755
index 9962e615..00000000
--- a/templates/rest/invoice/SearchInvoices.php
+++ /dev/null
@@ -1,38 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$parameters = array(
-    'email'                   => '',             // The initial letters of the email address.
-    'recipient_first_name'    => '' ,            // The initial letters of the recipient's first name.
-    'recipient_last_name'     => '',             // The initial letters of the recipient last name.
-    'recipient_business_name' => '',             // The initial letters of the recipient business name.
-    'number'                  => '',             // The invoice number.    
-    'start_invoice_date'      => '',             // The start date for the invoice. Date format is yyyy-MM-dd z, as defined in Internet Date/Time Format.
-    'end_invoice_date'        => '',             // The end date for the invoice. Date format is yyyy-MM-dd z, as defined in Internet Date/Time Format.
-    'start_due_date'          => '',             // The start due date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'end_due_date'            => '',             // The end due date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).  
-    'start_payment_date'      => '',             // The start payment date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6). 
-    'end_payment_date'        => '',             // The end payment date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'start_creation_date'     => '',             // The start creation date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'end_creation_date'       => '',             // The end creation date for the invoice. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).    
-    'page'                    => '',             // The offset for the search results.
-    'page_size'               => '',             // The page size for the search results.  
-    'total_count_required'    => '',             // Indicates whether the total count appears in the response. Default is `false`.    
-    'archived'                => '',             // A flag indicating whether search is on invoices archived by merchant. true - returns archived / false returns unarchived / null returns all.    
-);
-
-$returnArray = $PayPal->SearchInvoices($parameters);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/SendInvoice.php b/templates/rest/invoice/SendInvoice.php
deleted file mode 100755
index b32ca0cc..00000000
--- a/templates/rest/invoice/SendInvoice.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = '';    // Required. The ID of the invoice to send.
-
-$returnArray = $PayPal->SendInvoice($InvoiceID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/invoice/UpdateInvoice.php b/templates/rest/invoice/UpdateInvoice.php
deleted file mode 100755
index eafbda6b..00000000
--- a/templates/rest/invoice/UpdateInvoice.php
+++ /dev/null
@@ -1,176 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\invoice\InvoiceAPI($configArray);
-
-$InvoiceID = '';                                             // Required. The ID of the invoice to update.
-
-$merchantInfo = array(
-    'Email' => '',                                           // The merchant email address. Maximum length is 260 characters.
-    'FirstName' => '',                                       // The merchant first name. Maximum length is 30 characters.
-    'LastName'  => '',                                       // The merchant last name. Maximum length is 30 characters.        
-    'BusinessName' => '',                                    // The merchant company business name. Maximum length is 100 characters.
-);
-
-$merchantPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$merchantAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$billingInfo = array(
-    'Email' => '',                                            // The invoice recipient email address. Maximum length is 260 characters.
-    'FirstName' => '',                                        // The invoice recipient first name. Maximum length is 30 characters.
-    'LastName'  => '',                                        // The invoice recipient last name. Maximum length is 30 characters. 
-    'BusinessName' => '',                                     // The invoice recipient company business name. Maximum length is 100 characters.
-    'Language' => '',                                         // The language in which the email was sent to the payer. Used only when the payer does not have a PayPal account. Valid Values: ["da_DK", "de_DE", "en_AU", "en_GB", "en_US", "es_ES", "es_XC", "fr_CA", "fr_FR", "fr_XC", "he_IL", "id_ID", "it_IT", "ja_JP", "nl_NL", "no_NO", "pl_PL", "pt_BR", "pt_PT", "ru_RU", "sv_SE", "th_TH", "tr_TR", "zh_CN", "zh_HK", "zh_TW", "zh_XC"]
-    'AdditionalInfo' => '',                                   // Additional information, such as business hours. Maximum length is 40 characters.    
-    'NotificationChannel' => '',                              // Valid Values: ["SMS", "EMAIL"]. Preferred notification channel of the payer. Email by default.
-    
-);
-
-$billingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$billingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.         
-);
-  
-$itemArray = array();
-
-$item1 = array(
-    'Name' => '',                                           // Name of the item. 200 characters max.
-    'Description' => '',                                    // Description of the item. 1000 characters max.
-    'Quantity' => '',                                       // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => '',                   // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => ''                    // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. 
-                       ),                                   // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => '',                    // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '',                    // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                     // Tax associated with the item.
-    'Date' => '',                                           // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                      // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                  // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item1);
-
-$item2 = array(
-    'Name' => '',                                           // Name of the item. 200 characters max.
-    'Description' => '',                                    // Description of the item. 1000 characters max.
-    'Quantity' => '',                                       // Quantity of the item. Range of -10000 to 10000.
-    'UnitPrice'  => array(
-                        'Currency' => '',                   // 3 letter currency code as defined by ISO 4217.     
-                        'Value'    => ''                    // amount up to N digit after the decimals separator as defined in ISO 4217 for the appropriate currency code. 
-                       ),                                   // Unit price of the item. Range of -1,000,000 to 1,000,000.
-    'Tax' => array(
-                        'Name'    => '',                    // The tax name. Maximum length is 20 characters. 
-                        'Percent' => '',                    // The rate of the specified tax. Valid range is from 0.001 to 99.999.                        
-                     ),                                     // Tax associated with the item.
-    'Date' => '',                                           // The date when the item or service was provided. The date format is *yyyy*-*MM*-*dd* *z* as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).
-    'Discount' => array(
-                        'Percent' => '',                        
-                    ),                                      // The item discount, as a percent or an amount value.
-    'UnitOfMeasure' => '',                                  // Valid Values: ["QUANTITY", "HOURS", "AMOUNT"] The unit of measure of the item being invoiced.
-);
-
-array_push($itemArray,$item2);
-
-$finalDiscountForInvoice = array(
-    'Percent' => ''                                         // The rate of the specified Discount. Valid range is from 0.001 to 99.999.                         
-);
-
-$shippingInfo = array(
-    'FirstName' => '',                                      // The invoice recipient first name. Maximum length is 30 characters. 
-    'LastName'  => '',                                      // The invoice recipient last name. Maximum length is 30 characters.
-    'BusinessName' => '',                                   // The invoice recipient company business name. Maximum length is 100 characters.     
-);
-
-$shippingInfoPhone = array(
-    'CountryCode' => '',                                     // Country code (from in E.164 format).
-    'NationalNumber' => '',                                  // In-country phone number (from in E.164 format).
-    'Extension' => '',                                       // Phone extension.
-);
-
-$shippingInfoAddress = array(
-    'Line1' => '',                                            // Line 1 of the Address (eg. number, street, etc).
-    'Line2' => '',                                            // Optional line 2 of the Address (eg. suite, apt #, etc.).
-    'City'  => '',                                            // City name.
-    'CountryCode' => '',                                      // 2 letter country code.    
-    'PostalCode'  => '',                                      // Zip code or equivalent is usually required for countries that have them. For list of countries that do not have postal codes please refer to http://en.wikipedia.org/wiki/Postal_code. 
-    'State'       => '',                                      // 2 letter code for US states, and the equivalent for other countries.     
-);
-
-$paymentTerm = array(
-    'TermType' => '',                                         // Valid Values: ["DUE_ON_RECEIPT", "DUE_ON_DATE_SPECIFIED", "NET_10", "NET_15", "NET_30", "NET_45", "NET_60", "NET_90", "NO_DUE_DATE"]. The terms by which the invoice payment is due.
-    'DueDate'  => ''                                          // The date when the invoice payment is due. This date must be a future date. Date format is *yyyy*-*MM*-*dd* *z*, as defined in [Internet Date/Time Format](http://tools.ietf.org/html/rfc3339#section-5.6).   
-);
-
-$invoiceData = array(
-    'Note' => '',                                             // Note to the payer. 4000 characters max.
-    'Number' => '',                                           // Unique number that appears on the invoice. If left blank will be auto-incremented from the last number. 25 characters max.
-    'TemplateId' => '',                                       // The template ID used for the invoice. Useful for copy functionality.   
-    'Uri' => '',                                              // URI of the invoice resource.
-    'MerchantMemo' => '',                                     // A private bookkeeping memo for the merchant. Maximum length is 150 characters.
-    'LogoUrl'      => '',                                     // Full URL of an external image to use as the logo. Maximum length is 4000 characters.    
-);
-
-$attachments = array(
-    'Name' => '',                                             // Name of the file attached. 
-    'Url'  => ''                                              // URL of the attached file that can be downloaded.                                             // URL of the attached file that can be downloaded. 
-);
-
-$requestData =array(
-    'merchantInfo'            => $merchantInfo,
-    'merchantPhone'           => $merchantPhone,
-    'merchantAddress'         => $merchantAddress,
-    'billingInfo'             => $billingInfo,
-    'billingInfoPhone'        => $billingInfoPhone,
-    'billingInfoAddress'      => $billingInfoAddress,
-    'itemArray'               => $itemArray,
-    'finalDiscountForInvoice' => $finalDiscountForInvoice,
-    'shippingInfo'            => $shippingInfo,
-    'shippingInfoPhone'       => $shippingInfoPhone,
-    'shippingInfoAddress'     => $shippingInfoAddress,
-    'paymentTerm'             => $paymentTerm,
-    'invoiceData'             => $invoiceData,
-    'InvoiceID'               => $InvoiceID,
-    'attachments'             => $attachments
-);
-
-$returnArray = $PayPal->UpdateInvoice($requestData);
-echo "
";
-print_r($returnArray);
-
diff --git a/templates/rest/notifications/CreateWebhook.php b/templates/rest/notifications/CreateWebhook.php
deleted file mode 100644
index 62d6f3d0..00000000
--- a/templates/rest/notifications/CreateWebhook.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$event_types = array(
-    '', // The unique event name. You can fine list of webhooks name in PayPal_Webhooks.txt
-    ''
-);
-
-$url = "";          // The URL that is configured to listen on localhost for incoming POST notification messages that contain event information.
-
-$requestData = array(
-    'Url' => $url,
-    'EventTypes' => $event_types
-);
-
-$returnArray = $PayPal->CreateWebhook($requestData);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/DeleteWebhook.php b/templates/rest/notifications/DeleteWebhook.php
deleted file mode 100644
index f1e7caf6..00000000
--- a/templates/rest/notifications/DeleteWebhook.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '';  // The ID of the webhook to delete.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-
-$PayPalResult = $PayPal->DeleteWebhook($webhook_id);
-
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/templates/rest/notifications/EventNotificationDetails.php b/templates/rest/notifications/EventNotificationDetails.php
deleted file mode 100644
index 01d0fb7b..00000000
--- a/templates/rest/notifications/EventNotificationDetails.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$event_id  = '';     // The ID of the webhook event notification for which to show details.
-
-$returnArray = $PayPal->EventNotificationDetails($event_id);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/GetWebhook.php b/templates/rest/notifications/GetWebhook.php
deleted file mode 100644
index 71bfe620..00000000
--- a/templates/rest/notifications/GetWebhook.php
+++ /dev/null
@@ -1,24 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '';  // The ID of the webhook for which to show details.
-
-// Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->GetWebhook($webhook_id);
-
-// Write the contents of the response array to the screen for demo purposes.
-echo "
";
-print_r($PayPalResult);
diff --git a/templates/rest/notifications/ListEventSubscriptionsForWebhook.php b/templates/rest/notifications/ListEventSubscriptionsForWebhook.php
deleted file mode 100644
index 82881c9c..00000000
--- a/templates/rest/notifications/ListEventSubscriptionsForWebhook.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = ''; //  The ID of the webhook for which to list subscriptions.
-
-$returnArray = $PayPal->WebhooksEventTypesById($webhook_id);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/ListWebhooks.php b/templates/rest/notifications/ListWebhooks.php
deleted file mode 100644
index f659a5e2..00000000
--- a/templates/rest/notifications/ListWebhooks.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$anchor_type = '';  // Allowed values: APPLICATION, ACCOUNT. Default: APPLICATION. Filters the webhooks in the response by the anchor_id entity type.
-$requestData['anchor_type'] = $anchor_type;
-
-$returnArray = $PayPal->ListWebhooks($requestData);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/PayPal_Webhooks.txt b/templates/rest/notifications/PayPal_Webhooks.txt
deleted file mode 100644
index e532dda2..00000000
--- a/templates/rest/notifications/PayPal_Webhooks.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-BILLING.PLAN.CREATED
-BILLING.PLAN.UPDATED
-BILLING.SUBSCRIPTION.CANCELLED
-BILLING.SUBSCRIPTION.CREATED
-BILLING.SUBSCRIPTION.RE-ACTIVATED
-BILLING.SUBSCRIPTION.SUSPENDED
-BILLING.SUBSCRIPTION.UPDATED
-CHECKOUT.ORDER.COMPLETED
-CUSTOMER.DISPUTE.CREATED
-CUSTOMER.DISPUTE.RESOLVED
-CUSTOMER.DISPUTE.UPDATED
-CUSTOMER.MANAGED-ACCOUNT.CREATED
-CUSTOMER.MANAGED-ACCOUNT.RISK-ASSESSED
-CUSTOMER.MANAGED-ACCOUNT.UPDATED
-CUSTOMER.PAYOUT.FAILED
-IDENTITY.AUTHORIZATION-CONSENT.REVOKED
-INVOICING.INVOICE.CANCELLED
-INVOICING.INVOICE.CREATED
-INVOICING.INVOICE.PAID
-INVOICING.INVOICE.REFUNDED
-INVOICING.INVOICE.SCHEDULED
-INVOICING.INVOICE.UPDATED
-MERCHANT.ONBOARDING.COMPLETED
-MERCHANT.PARTNER-CONSENT.REVOKED
-PAYMENT-NETWORKS.ALTERNATIVE-PAYMENT.COMPLETED
-PAYMENT.AUTHORIZATION.CREATED
-PAYMENT.AUTHORIZATION.VOIDED
-PAYMENT.CAPTURE.COMPLETED
-PAYMENT.CAPTURE.DENIED
-PAYMENT.CAPTURE.PENDING
-PAYMENT.CAPTURE.REFUNDED
-PAYMENT.CAPTURE.REVERSED
-PAYMENT.ORDER.CANCELLED
-PAYMENT.ORDER.CREATED
-PAYMENT.PAYOUTS-ITEM.BLOCKED
-PAYMENT.PAYOUTS-ITEM.CANCELED
-PAYMENT.PAYOUTS-ITEM.DENIED
-PAYMENT.PAYOUTS-ITEM.FAILED
-PAYMENT.PAYOUTS-ITEM.HELD
-PAYMENT.PAYOUTS-ITEM.REFUNDED
-PAYMENT.PAYOUTS-ITEM.RETURNED
-PAYMENT.PAYOUTS-ITEM.SUCCEEDED
-PAYMENT.PAYOUTS-ITEM.UNCLAIMED
-PAYMENT.PAYOUTSBATCH.DENIED
-PAYMENT.PAYOUTSBATCH.PROCESSING
-PAYMENT.PAYOUTSBATCH.SUCCESS
-PAYMENT.SALE.COMPLETED
-PAYMENT.SALE.DENIED
-PAYMENT.SALE.PENDING
-PAYMENT.SALE.REFUNDED
-PAYMENT.SALE.REVERSED
-RISK.DISPUTE.CREATED
-VAULT.CREDIT-CARD.CREATED
-VAULT.CREDIT-CARD.DELETED
-VAULT.CREDIT-CARD.UPDATED
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/templates/rest/notifications/ResendEventNotification.php b/templates/rest/notifications/ResendEventNotification.php
deleted file mode 100644
index 6aacf17d..00000000
--- a/templates/rest/notifications/ResendEventNotification.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$event_id  = '';     // The ID of the webhook event notification for which to show details.
-
-$returnArray = $PayPal->ResendEventNotification($event_id);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/SearchWebhookEvents.php b/templates/rest/notifications/SearchWebhookEvents.php
deleted file mode 100644
index 43ea7ea2..00000000
--- a/templates/rest/notifications/SearchWebhookEvents.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$params = array(
-    'start_time'=>'',           // Filters the webhook event notifications in the response to those created on or after this date and time and on or before the end_time value.
-    'end_time'=>'',             // Filters the webhook event notifications in the response to those created on or after the start_time and on or before this date and time.
-    'page_size' => '',          // Default: 10. The number of webhook event notifications to return in the response.
-    'transaction_id' => '',     // Filters the response to a single transaction, by ID.
-    'event_type' =>''           // Filters the response to a single event.
-);
-
-$returnArray = $PayPal->SearchWebhookEvents($params);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/SimulateEvent.php b/templates/rest/notifications/SimulateEvent.php
deleted file mode 100644
index 5815c47b..00000000
--- a/templates/rest/notifications/SimulateEvent.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$params = array(
-    'webhook_id'=>'',                                 // The ID of the webhook. If omitted, the URL is required.
-    'url'=>'',                                        // The URL for the webhook endpoint. If omitted, the webhook ID is required.
-    'event_type' => '',                               // The event name. Specify one of the subscribed events. For each request, provide only one event.
-    'resource_version' => '',                         // The identifier for event type ex: 1.0/2.0 etc.
-);
-
-$returnArray = $PayPal->SimulateEvent($params);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/UpdateWebhook.php b/templates/rest/notifications/UpdateWebhook.php
deleted file mode 100644
index ae17367e..00000000
--- a/templates/rest/notifications/UpdateWebhook.php
+++ /dev/null
@@ -1,34 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$webhook_id = '';                                   // The ID of the webhook to update.
-
-$requestData = array(
-    array(
-        'Op' => '',                                  // The operation to complete. Valid Values: ["add", "remove", "replace", test"]
-        'Path'      => '',                           // The JSON pointer to the target document location at which to complete the operation.
-        'Value'     => ''                            // The value to apply. The remove operation does not require a value.
-    ),
-    array(
-        'Op' => '',                                  // The operation to complete. Valid Values: ["add", "remove", "replace", test"]
-        'Path'      => '',                           // The JSON pointer to the target document location at which to complete the operation.
-        'Value'     => ''                            // The value to apply. The remove operation does not require a value.
-    )
-);
-
-$returnArray = $PayPal->UpdateWebhook($webhook_id,$requestData);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/VerifyWebhookSignature.php b/templates/rest/notifications/VerifyWebhookSignature.php
deleted file mode 100644
index 082c6dab..00000000
--- a/templates/rest/notifications/VerifyWebhookSignature.php
+++ /dev/null
@@ -1,31 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$headers =array(
-    'auth_algo' => '',          // The algorithm that PayPal uses to generate the signature and that you can use to verify the signature. Extract this value from the PAYPAL-AUTH-ALGO response header, which is received with the webhook notification.
-    'cert_url' => '',           // The X.509 public key certificate. Download the certificate from this URL and use it to verify the signature. Extract this value from the PAYPAL-CERT-URL response header, which is received with the webhook notification.
-    'transmission_id' => '',    // The ID of the HTTP transmission. Contained in the PAYPAL-TRANSMISSION-ID header of the notification message.
-    'transmission_sig' => '',   // The PayPal-generated asymmetric signature. Appears in the PAYPAL-TRANSMISSION-SIG header of the notification message.
-    'transmission_time' => '',  // The date and time of the HTTP transmission, in Internet date and time format. Appears in the PAYPAL-TRANSMISSION-TIME header of the notification message.    
-);
-
-$webhook_id = '';               // The ID of the webhook as configured in your Developer Portal account.
-$webhook_event = file_get_contents('php://input');            // A webhook event notification.
-
-$returnArray = $PayPal->VerifyWebhookSignature($headers, $webhook_id,$webhook_content);
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/notifications/WebhooksEventTypes.php b/templates/rest/notifications/WebhooksEventTypes.php
deleted file mode 100644
index b299700d..00000000
--- a/templates/rest/notifications/WebhooksEventTypes.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\notifications\NotificationsAPI($configArray);
-
-$returnArray = $PayPal->WebhooksEventTypes();
-
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/payment/AuthorizationCapture.php b/templates/rest/payment/AuthorizationCapture.php
deleted file mode 100755
index 837eb7e8..00000000
--- a/templates/rest/payment/AuthorizationCapture.php
+++ /dev/null
@@ -1,25 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId='';                  //The Authorization ID of the payment.
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                         //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$returnArray = $PayPal->AuthorizationCapture($authorizationId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/CreatePayment.php b/templates/rest/payment/CreatePayment.php
deleted file mode 100755
index 3b05c1d5..00000000
--- a/templates/rest/payment/CreatePayment.php
+++ /dev/null
@@ -1,104 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='';                                                  //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.    
-
-$paymentCard = array(
-    'Type'              => '',                               // Required.  The card type.Possible values: VISA, AMEX, SOLO, JCB, STAR, DELTA, DISCOVER, SWITCH, MAESTRO, CB_NATIONALE, CONFINOGA, COFIDIS, ELECTRON, CETELEM, CHINA_UNION_PAY, MASTERCARD.
-    'Number'            => '',                               // Required.  The card number.  No spaces or punctuation.
-    'ExpireMonth'       => '',                               // Required.  The two-digit expiry month for the card.
-    'ExpireYear'        => '',                               // Required.  The four-digit expiry year for the card.
-    'Cvv2'              => '',                               // Required.  The validation code for the card. Supported for payments but not for saving payment cards for future use.
-    'FirstName'         => '',                               // Required.  The first name of the card holder.
-    'LastName'          => '',                               // The last name of the card holder.
-    'BillingCountry'    => '',                               // Required. The two-letter country code. For Example 'US'.
-    'StartMonth'        => '',                               // The two-digit start month for the card. Required for UK Maestro cards.
-    'StartYear'         => '',                               // The four-digit start year for the card. Required for UK Maestro cards. 
-    'ExternalCustomerId'=> '',                               // The externally-provided ID of the customer for whom to list credit cards.
-    'Status'            => '',                               // Possible values: EXPIRED, ACTIVE. The state of the funding instrument.
-    'CardProductClass'  => '',                               // Possible values: CREDIT, DEBIT, GIFT, PAYPAL_PREPAID, PREPAID, UNKNOWN. The product class of the financial instrument issuer.
-    'issue_number'      => ''                                // The one- to two-digit card issue number. Required for UK Maestro cards. Maximum length: 2.    
-);
-// billingAddress object with PaymentCard (Optional).
-$billingAddress = array(
-    'line1'        => '',                                    // Required.  First street address.
-    'line2'        => '',                                    // Optional line 2 of the Address
-    'city'         => '',                                    // Required.  Name of City.    
-    'state'        => '',                                    // Required. 2 letter code for US states, and the equivalent for other countries..
-    'postal_code'  => '',                                    // Required. postal code of your area.
-    'country_code' => '',                                    // 2 letter country code..   
-    'phone'        => ''                                     // Required.  Postal code of payer.
-);
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.
-    'Description' => '',                                     // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.
-    'Description' => '',                                     // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '',                                        // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '',                                        // Amount charged for shipping. 10 characters max with support for 2 decimal places. 
-    'Tax'      => '',                                        // Amount charged for tax. 10 characters max with support for 2 decimal places. 
-    'GiftWrap' => ''                                         // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'paymentCard'    => $paymentCard,
-    'billingAddress' => $billingAddress,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction
-);
-
-$returnArray = $PayPal->CreatePayment($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/CreatePaymentUsingPayPal.php b/templates/rest/payment/CreatePaymentUsingPayPal.php
deleted file mode 100755
index 3d9854c2..00000000
--- a/templates/rest/payment/CreatePaymentUsingPayPal.php
+++ /dev/null
@@ -1,82 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='';                                                 //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.    
-
-$urls= array(
-    'ReturnUrl'   => '',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => '',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => ''                                     // Required. 
-);
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.
-    'Description' => '',                                     // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.
-    'Description' => '',                                     // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '',                                        // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '',                                        // Amount charged for shipping. 10 characters max with support for 2 decimal places. 
-    'Tax'      => '',                                        // Amount charged for tax. 10 characters max with support for 2 decimal places. 
-    'GiftWrap' => ''                                         // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,    
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls
-);
-
-$returnArray = $PayPal->CreatePaymentUsingPayPal($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/CreatePaymentUsingSavedCardVault.php b/templates/rest/payment/CreatePaymentUsingSavedCardVault.php
deleted file mode 100755
index ce9d80e2..00000000
--- a/templates/rest/payment/CreatePaymentUsingSavedCardVault.php
+++ /dev/null
@@ -1,73 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='';                                              //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.    
-
-$cardID='';                                                // Saved credit card id from vault.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.    
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.   
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '',                                        // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '',                                        // Amount charged for shipping. 10 characters max with support for 2 decimal places. 
-    'Tax'      => '',                                        // Amount charged for tax. 10 characters max with support for 2 decimal places. 
-    'GiftWrap' => ''                                         // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction
-);
-
-$returnArray = $PayPal->CreatePaymentUsingSavedCardVault($requestData,$cardID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/CreateThirdPartyPayment.php b/templates/rest/payment/CreateThirdPartyPayment.php
deleted file mode 100644
index d3640b80..00000000
--- a/templates/rest/payment/CreateThirdPartyPayment.php
+++ /dev/null
@@ -1,101 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$intent='';                                             //Allowed values: sale, authorize, order.Payment intent. Must be set to sale for immediate payment, authorize to authorize a payment for capture later, or order to create an order.    
-
-// ### Notice
-// If your intent is "order" set this as URL array.
-// ReturnUrl=OrderGet.php?success=true 
-// CancelUrl=OrderGet.php?success=false
-//
-// ### For execute payment
-// If your intent is "sale" or "authorize" set this as URL array.
-//ReturnUrl=ExecutePayment.php?success=true
-//CancelUrl=ExecutePayment.php?success=false
-
-$third_party_merchant_email = '';                           // Specify a payee with that user's email or merchant id Merchant Id can be found at https://www.paypal.com/businessprofile/settings/
-
-$urls= array(
-    'ReturnUrl'   => '',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=true
-    'CancelUrl'   => '',                                    // Required when Pay using paypal. Example : ExecutePayment.php?success=false
-    'BaseUrl'     => ''                                     // Required. 
-);
-
-$invoiceNumber='';
-$ExperienceProfileId = '';                                   // Optional. PayPal generated identifier for the merchant's payment experience profile. Refer to [this](https://developer.paypal.com/docs/api/#payment-experience) link to create experience profile ID.
-$NoteToPayer = '';                                           // Optional. free-form field for the use of clients to pass in a message to the payer.
-
-$orderItems = array();
-$Item = array(
-    'Sku'         => '',                                     // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                     // Item name. 127 characters max.
-    'Description' => '',                                     // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '',                                     // Number of a particular item. 10 characters max
-    'Price'       => '',                                     // Item cost. 10 characters max. 
-    'Currency'    => '',                                     // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                      // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-$Item = array(
-    'Sku'         => '',                                    // Stock keeping unit corresponding (SKU) to item.
-    'Name'        => '',                                    // Item name. 127 characters max.
-    'Description' => '',                                    // Description of the item. Only supported when the `payment_method` is set to `paypal`.
-    'Quantity'    => '',                                    // Number of a particular item. 10 characters max
-    'Price'       => '',                                    // Item cost. 10 characters max. 
-    'Currency'    => '',                                    // 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/).
-    'Tax'         => ''                                     // Tax of the item. Only supported when the `payment_method` is set to `paypal`.    
-);
-array_push($orderItems, $Item);
-
-
-$paymentDetails = array(
-    'Subtotal' => '',                                       // Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
-    'Shipping' => '',                                       // Amount charged for shipping. 10 characters max with support for 2 decimal places. 
-    'Tax'      => '',                                       // Amount charged for tax. 10 characters max with support for 2 decimal places. 
-    'GiftWrap' => ''                                        // Amount being charged as gift wrap fee. 
-);
-
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$transaction = array(
-    'ReferenceId'    => '',                                 // Optional parameter. Merchant identifier to the purchase unit. Maximum length: 256. 
-    'Description'    => '',                                 // Payment description for particular transaction. Maximum length: 127.
-    'InvoiceNumber'  => '',                                 // Unique id of the Invoice. Maximum length: 127.
-    'Custom'         => '',                                 // free-form field for the use of clients. Maximum length: 127.
-    'SoftDescriptor' => '',                                 // Soft descriptor used when charging this funding source. If length exceeds max length, the value will be truncated. Maximum length: 22.
-    'NotifyUrl'      => '',                                 // URL to send payment notifications. Maximum length: 2048. Format: uri.
-    'OrderUrl'       => ''                                  // Url on merchant site pertaining to this payment. Maximum length: 2048. Format: uri.
-);
-
-$requestData = array(
-    'intent'         => $intent,    
-    'invoiceNumber' => $invoiceNumber,
-    'orderItems'     => $orderItems,
-    'paymentDetails' => $paymentDetails,
-    'amount'         => $amount,
-    'transaction'    => $transaction,
-    'urls'           => $urls,
-    'ExperienceProfileId' => $ExperienceProfileId,
-    'NoteToPayer'    => $NoteToPayer,
-    'Payee'          => $third_party_merchant_email
-);
-
-$returnArray = $PayPal->CreateThirdPartyPayment($requestData);
-print_r($returnArray);
diff --git a/templates/rest/payment/ExecutePayment.php b/templates/rest/payment/ExecutePayment.php
deleted file mode 100755
index c1be6723..00000000
--- a/templates/rest/payment/ExecutePayment.php
+++ /dev/null
@@ -1,64 +0,0 @@
-/execute'.
-
-$configArray = array(
-    'Sandbox' => $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-// ### Approval Status
-// Determine if the user approved the payment or not
-if (isset($_GET['success']) && $_GET['success'] == 'true') {
-
-    $paymentId = $_GET['paymentId'];
-    $payer_id = $_GET['PayerID'];
-
-    // ### Optional Changes to Amount
-    // If you wish to update the amount that you wish to charge the customer,
-    // based on the shipping address or any other reason, you could
-    // do that by passing the transaction object with just `amount` field in it.
-
-    $details = array(
-        'Shipping' => '',
-        'Tax' => '',
-        'HandlingFee' => '',
-        'ShippingDiscount' => '',
-        'Insurance' => '',
-        'GiftWrap' => '',
-        'Fee' => '',
-        'Subtotal' => ''
-    );
-
-
-    $amount = array(
-        'Currency' => '',
-        'Total' => '2',
-        'Details' => $details
-    );
-
-    $result = $PayPal->ExecutePayment($paymentId,$payer_id,$amount);
-    echo "
";
-    print_r($result);
-} else {
-    echo "User Cancelled the Approval";
-    exit;
-}
diff --git a/templates/rest/payment/GetAuthorization.php b/templates/rest/payment/GetAuthorization.php
deleted file mode 100755
index 5ee5f764..00000000
--- a/templates/rest/payment/GetAuthorization.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId='';                  //The Authorization ID of the payment for which to show details.
-
-$returnArray = $PayPal->GetAuthorization($authorizationId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/GetCapture.php b/templates/rest/payment/GetCapture.php
deleted file mode 100755
index 0c3ceeb3..00000000
--- a/templates/rest/payment/GetCapture.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationCaptureId = '';                       // Authorization Capture id you get from the Authorization Capture process.
-
-$returnArray = $PayPal->GetCapture($authorizationCaptureId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/ListPayments.php b/templates/rest/payment/ListPayments.php
deleted file mode 100755
index 648b14c3..00000000
--- a/templates/rest/payment/ListPayments.php
+++ /dev/null
@@ -1,27 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$params = array(
-    'count'       => '',            // Default: 10. The number of items to list in the response.
-    'start_index' => '',            // The ID of the starting resource in the response. When results are paged, you can use the next_id value as the start_id to continue with the next set of results.
-    'start_id'    => '',            // The start index of the resources to return. Typically used to jump to a specific position in the resource history based on its cart. Example for starting at the second item in a list of results: ?start_index=2
-    'start_time'  => '',            // The date and time when the resource was created. Indicates the start of a range of results. Example: start_time=2013-03-06T11:00:00Z
-    'end_time'    => '',            // The date and time when the resource was created. Indicates the end of a range of results. Format: date-time.
-);
-
-$returnArray = $PayPal->ListPayments($params);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/OrderAuthorize.php b/templates/rest/payment/OrderAuthorize.php
deleted file mode 100755
index c9e68bbf..00000000
--- a/templates/rest/payment/OrderAuthorize.php
+++ /dev/null
@@ -1,25 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$orderId = '';               // Replace $authorizationid with any static Id you might already have. It will do a void on it
-
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$returnArray = $PayPal->OrderAuthorize($orderId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/OrderCapture.php b/templates/rest/payment/OrderCapture.php
deleted file mode 100755
index e381f286..00000000
--- a/templates/rest/payment/OrderCapture.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$orderId = '';               // OrderId From Return Object/Array When Created Payment With Paypal/ OrderGet.php
-
-$amount = array(
-    'Currency' => '',                                       //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                       //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$returnArray = $PayPal->OrderCapture($orderId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/OrderDoVoid.php b/templates/rest/payment/OrderDoVoid.php
deleted file mode 100755
index 9deaca77..00000000
--- a/templates/rest/payment/OrderDoVoid.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$orderId = '';               // OrderId From Return Object/Array When Created Payment With Paypal/ OrderGet.php
-
-$returnArray = $PayPal->OrderDoVoid($orderId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/OrderGet.php b/templates/rest/payment/OrderGet.php
deleted file mode 100755
index 712549ba..00000000
--- a/templates/rest/payment/OrderGet.php
+++ /dev/null
@@ -1,48 +0,0 @@
-";
-
-
-if (isset($_GET['success']) && $_GET['success'] == 'true') {        
-
-    try {
-        
-        $paymentId = $_GET['paymentId'];
-        $payment = Payment::get($paymentId, $_api_context);
-        
-        $execution = new PaymentExecution();
-        $execution->setPayerId($_GET['PayerID']);
-
-        $payment=$payment->execute($execution, $_api_context);
-
-        $transactions = $payment->getTransactions();
-        $transaction = $transactions[0];
-        $relatedResources = $transaction->getRelatedResources();
-        $relatedResource = $relatedResources[0];
-        $order = $relatedResource->getOrder();
-        if(count(array_filter((array)$order)) > 0){
-            $result = \PayPal\Api\Order::get($order->getId(), $_api_context);
-            print_r($result->toArray());
-            print_r($payment->toArray());
-        }
-        else{
-            print_r($payment->toArray());
-        }
-        
-    } catch (\PayPal\Exception\PayPalConnectionException  $ex) {
-        var_dump($ex->getData());
-        exit;
-    }    
-} else {
-   echo "User Cancelled the Approval";
-   exit;
-}
diff --git a/templates/rest/payment/Reauthorization.php b/templates/rest/payment/Reauthorization.php
deleted file mode 100644
index 6b08c478..00000000
--- a/templates/rest/payment/Reauthorization.php
+++ /dev/null
@@ -1,47 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId = "";              // The ID of the authorization to re-authorize.
-
-$amount = array(
-    'Currency' => '',               //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',               //Required. The total amount charged to the payee by the payer. For refunds, represents the amount that the payee refunds to the original payer. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-    'Details'  => array(
-        'Subtotal' => '',           // The subtotal amount for the items. If the request includes line items, this property is required. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point. 
-        'Shipping' => '',           // The shipping fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'Tax'      => '',           // The tax. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'HandlingFee' => '',        // The handling fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'ShippingDiscount' => '',   // The shipping fee discount. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'Insurance' => '',          // The insurance fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'GiftWrap' => ''            // The gift wrap fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point.   
-    )
-);
-
-
-$returnArray = $PayPal->Reauthorization($authorizationId,$amount);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/RefundCapture.php b/templates/rest/payment/RefundCapture.php
deleted file mode 100755
index 21d3d903..00000000
--- a/templates/rest/payment/RefundCapture.php
+++ /dev/null
@@ -1,42 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$captureId = '';                                               // The ID of the captured payment to refund. AuthorizationCapture.php returns object with CaptureID.
-
-$amount = array(
-    'Currency' => '',                                          //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                                          //Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$refundParameters = array(
-    'Description'   => '',                                     // Description of what is being refunded for. Character length and limitations: 255 single-byte alphanumeric characters.
-    'RefundSource'  => '',                                     // Valid Values: ["INSTANT_FUNDING_SOURCE", "ECHECK", "UNRESTRICTED"]. Type of PayPal funding source (balance or eCheck) that can be used for auto refund.
-    'Reason'        => '',                                     // Reason description for the Sale transaction being refunded.
-    'InvoiceNumber' => '',                                     // The invoice number that is used to track this payment. Character length and limitations: 127 single-byte alphanumeric characters.
-    'RefundAdvice'  => ''                                      // Flag to indicate that the buyer was already given store credit for a given transaction.
-);
-
-$returnArray = $PayPal->RefundCapture($captureId,$amount,$refundParameters);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/ShowPaymentDetails.php b/templates/rest/payment/ShowPaymentDetails.php
deleted file mode 100755
index 404fcb2b..00000000
--- a/templates/rest/payment/ShowPaymentDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$PaymentID='';                  //The ID of the payment for which to show details.
-
-$returnArray = $PayPal->ShowPaymentDetails($PaymentID);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/ShowRefundDetails.php b/templates/rest/payment/ShowRefundDetails.php
deleted file mode 100644
index 8b84e9c4..00000000
--- a/templates/rest/payment/ShowRefundDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$refund_id ='';  // The ID of the refund for which to show details.
-
-$returnArray = $PayPal->ShowRefundDetails($refund_id);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/UpdatePayment.php b/templates/rest/payment/UpdatePayment.php
deleted file mode 100644
index 642d1d02..00000000
--- a/templates/rest/payment/UpdatePayment.php
+++ /dev/null
@@ -1,61 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$paymentId = '';                            // The ID of the payment to update.
-
-$patches = array();
-
-$array1 = array(
-    "operation" => "",                      // The operation to complete. Possible values: add, remove, replace, move, copy, test.
-    "path" => "",                           // The JSON pointer to the target document location at which to complete the operation.
-    "value" => array(                       // number,integer,string,boolean,null,array,object. The value to apply. The remove operation does not require a value.
-        'total' => '',
-        'currency' => '',
-        'details' => array(
-            'subtotal' => '',
-            'shipping' => '',
-            'tax' => ''
-        )
-    )
-);
-
-array_push($patches, $array1);
-
-$array2 = array(
-    "operation" => "",                                       // The operation to complete. Possible values: add, remove, replace, move, copy, test.
-    "path" => "",                                            // The JSON pointer to the target document location at which to complete the operation.
-    "value" => array(                                        // number,integer,string,boolean,null,array,object. The value to apply. The remove operation does not require a value.
-        'recipient_name' => '',
-        'line1' => '',
-        'city' => '',
-        "state" => "",
-        "postal_code" => "",
-        "country_code" => ""
-    )
-);
-
-array_push($patches, $array2);
-
-$returnArray = $PayPal->UpdatePayment($paymentId,$patches);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payment/VoidAuthorization.php b/templates/rest/payment/VoidAuthorization.php
deleted file mode 100755
index 0a618e6a..00000000
--- a/templates/rest/payment/VoidAuthorization.php
+++ /dev/null
@@ -1,21 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$authorizationId = ''; // Replace $authorizationid with any static Id you might already have. It will do a void on it
-
-$returnArray = $PayPal->VoidAuthorization($authorizationId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/paymentexperience/CreateWebProfile.php b/templates/rest/paymentexperience/CreateWebProfile.php
deleted file mode 100755
index 9fc3e645..00000000
--- a/templates/rest/paymentexperience/CreateWebProfile.php
+++ /dev/null
@@ -1,53 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$FlowConfig = array(
-    'LandingPageType'     => '',                                             // The type of landing page to display on the PayPal site for user checkout. Set to `Billing` to use the non-PayPal account landing page. Set to `Login` to use the PayPal account login landing page.
-    'BankTxnPendingUrl'   => '',                                             // The merchant site URL to display after a bank transfer payment. Valid for only the Giropay or bank transfer payment method in Germany.
-    'UserAction'          => '',                                             // Defines whether buyers can complete purchases on the PayPal or merchant website.
-    'ReturnUriHttpMethod' => '',                                             // Defines the HTTP method to use to redirect the user to a return URL. A valid value is `GET` or `POST`.    
-);
-
-$presentation = array(
-    'BrandName'           => '',                                             // A label that overrides the business name in the PayPal account on the PayPal pages. Character length and limitations: 127 single-byte alphanumeric characters.
-    'LogoImage'           => '',                                             // A URL to the logo image. A valid media type is `.gif`, `.jpg`, or `.png`. The maximum width of the image is 190 pixels. The maximum height of the image is 60 pixels. PayPal crops images that are larger. PayPal places your logo image at the top of the cart review area. PayPal recommends that you store the image on a secure (HTTPS) server. Otherwise, web browsers display a message that checkout pages contain non-secure items. Character length and limit: 127 single-byte alphanumeric characters.
-    'LocaleCode'          => '',                                             // The locale of pages displayed by PayPal payment experience. A valid value is `AU`, `AT`, `BE`, `BR`, `CA`, `CH`, `CN`, `DE`, `ES`, `GB`, `FR`, `IT`, `NL`, `PL`, `PT`, `RU`, or `US`. A 5-character code is also valid for languages in specific countries: `da_DK`, `he_IL`, `id_ID`, `ja_JP`, `no_NO`, `pt_BR`, `ru_RU`, `sv_SE`, `th_TH`, `zh_CN`, `zh_HK`, or `zh_TW`.
-    'ReturnUrlLabel'      => '',                                             // A label to use as hypertext for the return to merchant link.
-    'NoteToSellerLabel'   => '',                                             // A label to use as the title for the note to seller field. Used only when `allow_note` is `1`.    
-);
-
-$InputFields = array(
-    'AllowNote'           => '',                                             // Type bool. Indicates whether the buyer can enter a note to the merchant on the PayPal page during checkout.
-    'NoShipping'          => '',                                             // Indicates whether PayPal displays shipping address fields on the experience pages. Valid value is `0`, `1`, or `2`. Set to `0` to display the shipping address on the PayPal pages. Set to `1` to redact shipping address fields from the PayPal pages. Set to `2` to not pass the shipping address but instead get it from the buyer's account profile. For digital goods, this field is required and value must be `1`.
-    'AddressOverride'     => '',                                             // Indicates whether to display the shipping address that is passed to this call rather than the one on file with PayPal for this buyer on the PayPal experience pages. Valid value is `0` or `1`. Set to `0` to display the shipping address on file. Set to `1` to display the shipping address supplied to this call; the buyer cannot edit this shipping address.    
-);
-
-$WebProfile = array(
-    'Name'                => '',                                             // The web experience profile name. Unique for a specified merchant's profiles.
-    'Temporary'           => '',                                             // Indicates whether the profile persists for three hours or permanently. Set to `false` to persist the profile permanently. Set to `true` to persist the profile for three hours.    
-);
-
-$requestData = array(
-    'FlowConfig'   => $FlowConfig,
-    'presentation' => $presentation,
-    'InputFields'  => $InputFields,
-    'WebProfile'   => $WebProfile
-);
-
-$returnArray = $PayPal->CreateWebProfile($requestData);
-echo "
";
-print_r($returnArray);
-
diff --git a/templates/rest/paymentexperience/DeleteWebProfile.php b/templates/rest/paymentexperience/DeleteWebProfile.php
deleted file mode 100755
index 6bc07631..00000000
--- a/templates/rest/paymentexperience/DeleteWebProfile.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$ProfileID = '';       // Required. The ID of the profile for which to show details.
-
-$returnArray = $PayPal->DeleteWebProfile($ProfileID);
-echo "
";
-print_r($returnArray);
-
diff --git a/templates/rest/paymentexperience/GetWebProfile.php b/templates/rest/paymentexperience/GetWebProfile.php
deleted file mode 100755
index 60a71a82..00000000
--- a/templates/rest/paymentexperience/GetWebProfile.php
+++ /dev/null
@@ -1,22 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$ProfileID = '';       // Required. The ID of the profile for which to show details.
-
-$returnArray = $PayPal->GetWebProfile($ProfileID);
-echo "
";
-print_r($returnArray);
-
diff --git a/templates/rest/paymentexperience/ListWebProfiles.php b/templates/rest/paymentexperience/ListWebProfiles.php
deleted file mode 100755
index 29e2079e..00000000
--- a/templates/rest/paymentexperience/ListWebProfiles.php
+++ /dev/null
@@ -1,19 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$returnArray = $PayPal->ListWebProfiles();
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/paymentexperience/PartiallyUpdateWebProfile.php b/templates/rest/paymentexperience/PartiallyUpdateWebProfile.php
deleted file mode 100755
index faec02d8..00000000
--- a/templates/rest/paymentexperience/PartiallyUpdateWebProfile.php
+++ /dev/null
@@ -1,38 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-$profileID = '';                                          // Required.  The ID of the profile to update.
-
-$patchArray = array();
-
-$array1 = array(
-    'Op'      => '',                                      // The operation to perform. Valid Values: ["add", "remove", "replace", "move", "copy", "test"]
-    'Path'    => '',                                      // A JSON pointer that references a location in the target document where the operation is performed. A `string` value.
-    'Value'   => '',                                      // New value to apply based on the operation.
-);
-array_push($patchArray,$array1);
-
-$array2 = array(
-    'Op'      => '',                                      // The operation to perform. Valid Values: ["add", "remove", "replace", "move", "copy", "test"]
-    'Path'    => '',                                      // A JSON pointer that references a location in the target document where the operation is performed. A `string` value.
-    'Value'   => '',                                      // New value to apply based on the operation.
-);
-array_push($patchArray,$array2);
-
-$returnArray = $PayPal->PartiallyUpdateWebProfile($patchArray,$profileID);
-echo "
";
-print_r($returnArray);
-
diff --git a/templates/rest/paymentexperience/UpdateWebProfile.php b/templates/rest/paymentexperience/UpdateWebProfile.php
deleted file mode 100755
index de4e26e4..00000000
--- a/templates/rest/paymentexperience/UpdateWebProfile.php
+++ /dev/null
@@ -1,56 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paymentexperience\PaymentExperianceAPI($configArray);
-
-
-$profileID = '';                                                             // Required. The ID of the profile to update.
-
-$FlowConfig = array(
-    'LandingPageType'     => '',                                             // The type of landing page to display on the PayPal site for user checkout. Set to `Billing` to use the non-PayPal account landing page. Set to `Login` to use the PayPal account login landing page.
-    'BankTxnPendingUrl'   => '',                                             // The merchant site URL to display after a bank transfer payment. Valid for only the Giropay or bank transfer payment method in Germany.
-    'UserAction'          => '',                                             // Defines whether buyers can complete purchases on the PayPal or merchant website.
-    'ReturnUriHttpMethod' => '',                                             // Defines the HTTP method to use to redirect the user to a return URL. A valid value is `GET` or `POST`.    
-);
-
-$presentation = array(
-    'BrandName'           => '',                                             // A label that overrides the business name in the PayPal account on the PayPal pages. Character length and limitations: 127 single-byte alphanumeric characters.
-    'LogoImage'           => '',                                             // A URL to the logo image. A valid media type is `.gif`, `.jpg`, or `.png`. The maximum width of the image is 190 pixels. The maximum height of the image is 60 pixels. PayPal crops images that are larger. PayPal places your logo image at the top of the cart review area. PayPal recommends that you store the image on a secure (HTTPS) server. Otherwise, web browsers display a message that checkout pages contain non-secure items. Character length and limit: 127 single-byte alphanumeric characters.
-    'LocaleCode'          => '',                                             // The locale of pages displayed by PayPal payment experience. A valid value is `AU`, `AT`, `BE`, `BR`, `CA`, `CH`, `CN`, `DE`, `ES`, `GB`, `FR`, `IT`, `NL`, `PL`, `PT`, `RU`, or `US`. A 5-character code is also valid for languages in specific countries: `da_DK`, `he_IL`, `id_ID`, `ja_JP`, `no_NO`, `pt_BR`, `ru_RU`, `sv_SE`, `th_TH`, `zh_CN`, `zh_HK`, or `zh_TW`.
-    'ReturnUrlLabel'      => '',                                             // A label to use as hypertext for the return to merchant link.
-    'NoteToSellerLabel'   => '',                                             // A label to use as the title for the note to seller field. Used only when `allow_note` is `1`.    
-);
-
-$InputFields = array(
-    'AllowNote'           => '',                                             // Type bool. Indicates whether the buyer can enter a note to the merchant on the PayPal page during checkout.
-    'NoShipping'          => '',                                             // Indicates whether PayPal displays shipping address fields on the experience pages. Valid value is `0`, `1`, or `2`. Set to `0` to display the shipping address on the PayPal pages. Set to `1` to redact shipping address fields from the PayPal pages. Set to `2` to not pass the shipping address but instead get it from the buyer's account profile. For digital goods, this field is required and value must be `1`.
-    'AddressOverride'     => '',                                             // Indicates whether to display the shipping address that is passed to this call rather than the one on file with PayPal for this buyer on the PayPal experience pages. Valid value is `0` or `1`. Set to `0` to display the shipping address on file. Set to `1` to display the shipping address supplied to this call; the buyer cannot edit this shipping address.    
-);
-
-$WebProfile = array(
-    'Name'                => '',                                             // Required. | The web experience profile name. Unique for a specified merchant's profiles.
-    'Temporary'           => '',                                             // Indicates whether the profile persists for three hours or permanently. Set to `false` to persist the profile permanently. Set to `true` to persist the profile for three hours.    
-);
-
-$requestData = array(
-    'FlowConfig'   => $FlowConfig,
-    'presentation' => $presentation,
-    'InputFields'  => $InputFields,
-    'WebProfile'   => $WebProfile
-);
-
-$returnArray = $PayPal->UpdateWebProfile($requestData,$profileID);
-echo "
";
-print_r($returnArray);
-
diff --git a/templates/rest/payouts/CancelPayoutItem.php b/templates/rest/payouts/CancelPayoutItem.php
deleted file mode 100755
index 6b8a796b..00000000
--- a/templates/rest/payouts/CancelPayoutItem.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret
-);
-
-$PayPal = new angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-//## Payout Item ID you get when you create Mass payment single/batch.
-
-$payoutItemId='';                  // Required. The ID of the Payout Item for which to show details.
-
-$returnArray = $PayPal->CancelPayoutItem($payoutItemId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payouts/CreateBatchPayout.php b/templates/rest/payouts/CreateBatchPayout.php
deleted file mode 100755
index 72d064cf..00000000
--- a/templates/rest/payouts/CreateBatchPayout.php
+++ /dev/null
@@ -1,68 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret
-);
-
-$PayPal = new \angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-$batchHeader = array(
-    'SenderBatchId' => uniqid(),                                   // A sender-specified ID number. Tracks the batch payout in an accounting system.Note: PayPal prevents duplicate batches from being processed. If you specify a `sender_batch_id` that was used in the last 30 days, the API rejects the request and returns an error message that indicates the duplicate `sender_batch_id` and includes a HATEOAS link to the original batch payout with the same `sender_batch_id`. If you receive a HTTP `5nn` status code, you can safely retry the request with the same `sender_batch_id`. In any case, the API completes a payment only once for a specific `sender_batch_id` that is used within 30 days.
-    'EmailSubject'  => '',          // The subject line text for the email that PayPal sends when a payout item completes. The subject line is the same for all recipients. Value is an alphanumeric string with a maximum length of 255 single-byte characters.    
-);
-
-$amount = array(
-    'currency' => '',                                    // Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'value'    => '',                                      // Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$PayoutItem = array();
-
-$PayoutItem1 = array(
-    //  ### RecipientType 
-    //  Valid values: EMAIL | PHONE | PAYPAL_ID. 
-    //  The type of ID that identifies the payment receiver.
-    //  EMAIL. Unencrypted email. Value is a string of up to 127 single-byte characters.
-    //  PHONE. Unencrypted phone number.
-    //  Note: The PayPal sandbox does not support the PHONE recipient type.
-    //  PAYPAL_ID Encrypted PayPal account number.
-    
-    'RecipientType' => '',                                 // Valid values: EMAIL | PHONE | PAYPAL_ID.      
-    'Note'          => '',            // Optional. A sender-specified note for notifications. Value is any string value. Maximum length: 4000.
-    'Receiver'      => '',    // The receiver of the payment. Corresponds to the recipient_type value in the request. Maximum length: 127.
-    'SenderItemId'  => uniqid(),                         // A sender-specified ID number. Tracks the batch payout in an accounting system. Maximum length: 30.    
-);
-
-array_push($PayoutItem, $PayoutItem1);
-
-$PayoutItem2 = array(
-    //  ### RecipientType 
-    //  Valid values: EMAIL | PHONE | PAYPAL_ID. 
-    //  The type of ID that identifies the payment receiver.
-    //  EMAIL. Unencrypted email. Value is a string of up to 127 single-byte characters.
-    //  PHONE. Unencrypted phone number.
-    //  Note: The PayPal sandbox does not support the PHONE recipient type.
-    //  PAYPAL_ID Encrypted PayPal account number.
-    
-    'RecipientType' => '',                                 // Valid values: EMAIL | PHONE | PAYPAL_ID.      
-    'Note'          => '',            // Optional. A sender-specified note for notifications. Value is any string value. Maximum length: 4000.
-    'Receiver'      => '',    // The receiver of the payment. Corresponds to the recipient_type value in the request. Maximum length: 127.
-    'SenderItemId'  => uniqid(),                         // A sender-specified ID number. Tracks the batch payout in an accounting system. Maximum length: 30.    
-);
-
-array_push($PayoutItem, $PayoutItem2);
-
-$requestData=array(    
-    "batchHeader" => $batchHeader,
-    "amount"      => $amount,
-    "PayoutItem"  => $PayoutItem
-);
-
-$returnArray = $PayPal->CreateBatchPayout($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payouts/CreateSinglePayout.php b/templates/rest/payouts/CreateSinglePayout.php
deleted file mode 100755
index 951cd3bf..00000000
--- a/templates/rest/payouts/CreateSinglePayout.php
+++ /dev/null
@@ -1,47 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret
-);
-
-$PayPal = new \angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-$batchHeader = array(
-    'SenderBatchId' => uniqid(),                                   // A sender-specified ID number. Tracks the batch payout in an accounting system.Note: PayPal prevents duplicate batches from being processed. If you specify a `sender_batch_id` that was used in the last 30 days, the API rejects the request and returns an error message that indicates the duplicate `sender_batch_id` and includes a HATEOAS link to the original batch payout with the same `sender_batch_id`. If you receive a HTTP `5nn` status code, you can safely retry the request with the same `sender_batch_id`. In any case, the API completes a payment only once for a specific `sender_batch_id` that is used within 30 days.
-    'EmailSubject'  => '',          // The subject line text for the email that PayPal sends when a payout item completes. The subject line is the same for all recipients. Value is an alphanumeric string with a maximum length of 255 single-byte characters.    
-);
-
-$amount = array(
-    'currency' => '',                                    // Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'value'    => '',                                      // Required. Total amount charged from the payer to the payee. In case of a refund, this is the refunded amount to the original payer from the payee. 10 characters max with support for 2 decimal places. 
-);
-
-$PayoutItem = array(
-    //  ### RecipientType 
-    //  Valid values: EMAIL | PHONE | PAYPAL_ID. 
-    //  The type of ID that identifies the payment receiver.
-    //  EMAIL. Unencrypted email. Value is a string of up to 127 single-byte characters.
-    //  PHONE. Unencrypted phone number.
-    //  Note: The PayPal sandbox does not support the PHONE recipient type.
-    //  PAYPAL_ID Encrypted PayPal account number.
-    
-    'RecipientType' => '',                                 // Valid values: EMAIL | PHONE | PAYPAL_ID.      
-    'Note'          => '',            // Optional. A sender-specified note for notifications. Value is any string value. Maximum length: 4000.
-    'Receiver'      => '',    // The receiver of the payment. Corresponds to the recipient_type value in the request. Maximum length: 127.
-    'SenderItemId'  => '',                         // A sender-specified ID number. Tracks the batch payout in an accounting system. Maximum length: 30.    
-);
-
-$requestData=array(    
-    "batchHeader" => $batchHeader,
-    "amount"      => $amount,
-    "PayoutItem"  => $PayoutItem
-);
-
-$returnArray = $PayPal->CreateSinglePayout($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payouts/GetPayoutBatchStatus.php b/templates/rest/payouts/GetPayoutBatchStatus.php
deleted file mode 100755
index e6391d56..00000000
--- a/templates/rest/payouts/GetPayoutBatchStatus.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret
-);
-
-$PayPal = new angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-//## Payout Batch ID you get when you create Mass payment single/batch.
-
-$payoutBatchId='';                  // Required. The ID of the payout batch for which to show details.
-
-$returnArray = $PayPal->GetPayoutBatchStatus($payoutBatchId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/payouts/GetPayoutItemStatus.php b/templates/rest/payouts/GetPayoutItemStatus.php
deleted file mode 100755
index 1f1a9dd0..00000000
--- a/templates/rest/payouts/GetPayoutItemStatus.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret
-);
-
-$PayPal = new angelleye\PayPal\rest\payouts\PayoutsAPI($configArray);
-
-//## Payout Item ID you get when you create Mass payment single/batch.
-
-$payoutItemId='';                  // Required. The ID of the Payout Item for which to show details.
-
-$returnArray = $PayPal->GetPayoutItemStatus($payoutItemId);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/paypal_sync/paypal_sync_transactions.php b/templates/rest/paypal_sync/paypal_sync_transactions.php
deleted file mode 100644
index c91fa586..00000000
--- a/templates/rest/paypal_sync/paypal_sync_transactions.php
+++ /dev/null
@@ -1,43 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\paypal_sync\PayPalSyncAPI($configArray);
-
-$parameters = array(
-    'transaction_id' => '',                                 // Filters the transactions in the response by a PayPal transaction ID. A valid transaction ID is 17 characters long, except for an order ID, which is 19 characters long. Minimum length: 17.Maximum length: 19.
-    'transaction_type' => '',                               // Filters the transactions in the response by a PayPal transaction event code. See Transaction event codes. https://developer.paypal.com/docs/integration/direct/sync/transaction-event-codes/
-    'transaction_status' => '',                             // Filters the transactions in the response by a PayPal transaction status code. Value is: 
-                                                            // D : PayPal or merchant rules denied the transaction.
-                                                            // F : The original recipient partially refunded the transaction.
-                                                            // P : The transaction is pending. The transaction was created but waits for another payment process to complete, such as an ACH transaction, before the status changes to S.
-                                                            // S : The transaction successfully completed without a denial and after any pending statuses.
-                                                            // V : A successful transaction was reversed and funds were refunded to the original sender.
-    'transaction_amount' => '',                             // Filters the transactions in the response by a gross transaction amount range. Specify the range as  TO , where  is the lower limit of the gross PayPal transaction amount and  is the upper limit of the gross transaction amount. Specify the amounts in lower denominations. For example, to search for transactions from $5.00 to $10.05, specify [500 TO 1005].
-    'transaction_currency' => '',                           // PayPal transaction currency.
-    'start_date' => '',                                     // Example : 2017-07-01T00:00:00-0700 Filters the transactions in the response by a start date and time Minimum length: 20.Maximum length: 64. 
-    'end_date' => '',                                       // Example : 2017-07-30T00:00:00-0700 Filters the transactions in the response by a end date and time Minimum length: 20.Maximum length: 64. 
-    'payment_instrument_type' => '',                        // CREDITCARD | DEBITCARD | Filters the transactions in the response by a payment instrument type, If you omit this parameter, the API does not apply this filter.
-    'store_id'  => '' ,                                     // Filters the transactions in the response by a store ID.
-    'terminal_id' => '',                                    // Filters the transactions in the response by a terminal ID.
-    'fields' => 'all',                                      // Indicates which fields appear in the response. Value is a single field or a comma-separated list of fields. Other fields are : transaction_info | payer_info | shipping_info | auction_info | cart_info | incentive_info | store_info
-    'balance_affecting_records_only' =>  '',                // Indicates whether the response includes only balance-impacting transactions or all transactions. Value is either: Y. The default. The response includes only balance transactions. N. The response includes all transactions.
-    'page_size' => '',                                      // Minimum value: 1.  Maximum value: 500. The number of items to return in the response.   
-    'page' => ''                                            // Minimum value: 1. Maximum value: 2147483647.                
-);
-
-$response = $PayPal->PaypalSyncTransactions($parameters);
-
-echo "
";
-print_r($response);
-exit;
diff --git a/templates/rest/referenced_payouts/create_referenced_batch_payout.php b/templates/rest/referenced_payouts/create_referenced_batch_payout.php
deleted file mode 100644
index 8344b7f2..00000000
--- a/templates/rest/referenced_payouts/create_referenced_batch_payout.php
+++ /dev/null
@@ -1,99 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-
-$PayPal = new \angelleye\PayPal\rest\referenced_payouts\ReferencedPayoutsAPI($configArray);
-
-// Header parameters
-$PayPal_Partner_Attribution_Id = ''; // For more information about PayPal-Partner-Attribution-Id, see https://developer.paypal.com/docs/api/overview/#paypal-partner-attribution-id
-
-/*  Indicates how the client expects the server to process this request.
- *  To process the request asynchronously, set this header to respond-async.
- *  If you omit this header, the API processes the request synchronously.
- *  For synchronous processing the application may levy additional checks on the number of supported items
- *  in the request and may fail the request if those limits are breached.
- */
-$Prefer = '';
-$PayPal_Request_Id = '';          // The server stores keys for three days. For more information about PayPal-Request-Id, see https://developer.paypal.com/docs/api/overview/#paypal-request-id
-
-if(!empty($Prefer)) {
-    $PayPal->set_prefer($Prefer);
-}
-if(!empty($PayPal_Request_Id)) {
-    $PayPal->set_paypal_request_id($PayPal_Request_Id);
-}
-
-$referenced_payouts_items = array();
-
-$processing_state_1 = array(
-    'status' => '',         // PENDING | PROCESSING | SUCCESS | FAILED | PAYOUT_FAILED | The item status.
-    'reason' => ''          // INTERNAL_ERROR | NOT_ENOUGH_BALANCE | AMOUNT_CHECK_FAILED | MERCHANT_PARTNER_PERMISSIONS_ISSUE | MERCHANT_RESTRICTIONS | TRANSACTION_UNDER_DISPUTE |TRANSACTION_NOT_VALID | UNSUPPORTED_CURRENCY |PAYOUT_INITIATED | The reason code.
-);
-
-$payout_amount = array(
-    'currency_code' => '',  // The three-character ISO-4217 currency code that identifies the currency.
-    'value' => ''           // Maximum length: 32. | Pattern: ^((-?[0-9]+)|(-?([0-9]+)?[.][0-9]+))$
-);
-
-$referenced_payouts_item_1 = array(
-    'item_id' => '',                        // The ID for the payout item request.
-    'processing_state' => array_filter($processing_state_1),               // The processing state of the reference payout.
-    'reference_id' => '',                   // The original reference ID, based on reference_type, based on the type payout.
-    'reference_type' => '',                 // TRANSACTION_ID | OTHERS | The reference type.
-    'payout_transaction_id' => '',          // The encrypted PayPal transaction ID for the payout when the item_status is success.
-    'disbursement_transaction_id' => '',    // The encrypted PayPal transaction ID for the disbursement when the money is moved from settlement hold to receiver.
-    'external_merchant_id' => '',           // The unique ID for the merchant on the partner side. Can be used to retrieve the PayPal account linked to this ID for the payout.
-    'external_reference_id' => '',          // The unique ID for the request on the partner side to enable idempotency. If this parameter is not available, idempotency is enabled for this item.
-    'payee_email' => '',                    // The PayPal merchant account email that receives the payout. Can be used to override the default behavior where the payout receiver is derived from the reference that is passed.
-    'payout_amount' => array_filter($payout_amount),      // The amount to be paid to merchant. 
-    'payout_destination' => '',             // The encrypted PayPal account number or the ID of the financial instrument that received the payout.
-    'invoice_id' => '',                     // The partner invoice ID for this referenced-payouts item. Used for reporting purposes only.
-    'custom' =>''                           // The partner custom data for this referenced-payouts item. Used for reporting purposes only.
-);
-
-array_push($referenced_payouts_items, array_filter($referenced_payouts_item_1));
-
-$referenced_payouts_item_2 = array(
-    'item_id' => '',                        // The ID for the payout item request.
-    'processing_state' => array_filter($processing_state_1),               // The processing state of the reference payout.
-    'reference_id' => '',                   // The original reference ID, based on reference_type, based on the type payout.
-    'reference_type' => '',                 // TRANSACTION_ID | OTHERS | The reference type.
-    'payout_transaction_id' => '',          // The encrypted PayPal transaction ID for the payout when the item_status is success.
-    'disbursement_transaction_id' => '',    // The encrypted PayPal transaction ID for the disbursement when the money is moved from settlement hold to receiver.
-    'external_merchant_id' => '',           // The unique ID for the merchant on the partner side. Can be used to retrieve the PayPal account linked to this ID for the payout.
-    'external_reference_id' => '',          // The unique ID for the request on the partner side to enable idempotency. If this parameter is not available, idempotency is enabled for this item.
-    'payee_email' => '',                    // The PayPal merchant account email that receives the payout. Can be used to override the default behavior where the payout receiver is derived from the reference that is passed.
-    'payout_amount' => array_filter($payout_amount),      // The amount to be paid to merchant. 
-    'payout_destination' => '',             // The encrypted PayPal account number or the ID of the financial instrument that received the payout.
-    'invoice_id' => '',                     // The partner invoice ID for this referenced-payouts item. Used for reporting purposes only.
-    'custom' =>''                           // The partner custom data for this referenced-payouts item. Used for reporting purposes only.
-);
-
-array_push($referenced_payouts_items, array_filter($referenced_payouts_item_2));
-
-$referenced_payouts  = $referenced_payouts_items;
-
-$payout_directive = array(
-    'financial_instrument_id' => ''                       // Minimum length: 1. Maximum length: 255. The PayPal-provided ID of the financial instrument that receives the payout. If you omit this value, the payout is made to the receiver's balance by default. If you include payee_email to override the original receiver on the individual item or items, the API ignores this field.
-);
-
-$parameters = array(    
-    'referenced_payouts' => $referenced_payouts,          // An array of referenced payouts items. For synchronous execution, the maximum number of items is 10. If you include more than 10 items, the request is processed asynchronously no matter what the partner defined in the Prefer request header.
-    'payout_directive' => array_filter($payout_directive) // The payout directive. Defines how the payout is made following the referenced payouts, if required. If you include this directive, all items in the request must be for the same original receiver. Otherwise, the request fails. You can override the payout directive at the item level to a different funding instrument, if required.
-);
-
-$response = $PayPal->CreateReferencedBatchPayout($parameters);
-
-echo "
";
-print_r($response);
-exit;
\ No newline at end of file
diff --git a/templates/rest/sale/GetSale.php b/templates/rest/sale/GetSale.php
deleted file mode 100644
index d2a7a130..00000000
--- a/templates/rest/sale/GetSale.php
+++ /dev/null
@@ -1,26 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$sale_id = ''; // The ID of the sale for which to show details.
-
-$returnArray = $PayPal->GetSale($sale_id);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/sale/RefundSale.php b/templates/rest/sale/RefundSale.php
deleted file mode 100644
index 51858f97..00000000
--- a/templates/rest/sale/RefundSale.php
+++ /dev/null
@@ -1,46 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results, 
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level  
-);
-$PayPal = new angelleye\PayPal\rest\payments\PaymentAPI($configArray);
-
-$sale_id = '';         // The ID of the sale transaction to refund.
-
-$amount = array(
-    'Currency' => '',                   //Required. 3-letter [currency code](https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/). PayPal does not support all currencies. 
-    'Total'    => '',                   //Required. The total amount charged to the payee by the payer. For refunds, represents the amount that the payee refunds to the original payer. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-    'Details'  => array(
-        'Subtotal' => '',               // The subtotal amount for the items. If the request includes line items, this property is required. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point. 
-        'Shipping' => '',               // The shipping fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'Tax'      => '',               // The tax. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point. 3) Two digits after the decimal point.
-        'HandlingFee' => '',            // The handling fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'ShippingDiscount' => '',       // The shipping fee discount. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'Insurance' => '',              // The insurance fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point. Supported for the PayPal payment method only.
-        'GiftWrap' => ''                // The gift wrap fee. Maximum length is 10 characters, which includes: 1) Seven digits before the decimal point. 2) The decimal point.  3) Two digits after the decimal point.   
-    )
-);
-
-$refundParameters = array(
-    'Description'   => '',                                      // The refund description. Value is a string of single-byte alphanumeric characters. Maximum length: 255.    
-    'Reason'        => '',                                      // The refund reason description. Maximum length: 30.
-    'InvoiceNumber' => '',                                      // The invoice number that tracks this payment. Value is a string of single-byte alphanumeric characters. Maximum length: 127.
-);
-
-$returnArray = $PayPal->RefundSale($sale_id,$amount,$refundParameters);
-echo "
";
-print_r($returnArray);
\ No newline at end of file
diff --git a/templates/rest/vault/DeleteCreditCard.php b/templates/rest/vault/DeleteCreditCard.php
deleted file mode 100755
index 2b019c75..00000000
--- a/templates/rest/vault/DeleteCreditCard.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$requestData=array(
-                'credit_card_id' => ''             //Required.The credit_card_id is the ID of the stored credit card. 
-            );
-
-$returnArray = $PayPal->DeleteCreditCard($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/vault/GetCardDetails.php b/templates/rest/vault/GetCardDetails.php
deleted file mode 100644
index 2a653182..00000000
--- a/templates/rest/vault/GetCardDetails.php
+++ /dev/null
@@ -1,23 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$requestData=array(
-                'credit_card_id' => ''             // Required. The credit_card_id is the ID of the stored credit card. 
-            );
-
-$returnArray = $PayPal->GetCardDetails($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/vault/ListCreditCards.php b/templates/rest/vault/ListCreditCards.php
deleted file mode 100755
index 00054ed4..00000000
--- a/templates/rest/vault/ListCreditCards.php
+++ /dev/null
@@ -1,32 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$requestData=array(
-                'sort_by' => '',                        //Default is create_time. Sorts the vaulted credit cards in the response by either create_time or update_time.      
-                'sort_order' => '',                     //Default: desc.Value is asc for ascending order or desc for descending order.
-                'merchant_id' => '',                    // Filtering by MerchantId set during CreateCreditCard.
-                'page_size'  => '',                     //Default: 10. The number of vaulted credit cards to return in the response beginning with the specified   
-                'page'=>'',                             //Default: 1. A zero-relative index of the list of vaulted credit cards.
-                'start_time' =>'',                      //For example, 2016-11-05T13:15:30Z. Filters the vaulted credit cards in the response to those created on.  
-                'end_time' => ''  ,                     //Filters the vaulted credit cards in the response to those created on or after the start_time date and time and on or before this value 
-                'external_card_id'=>'',                 //Filters the vaulted credit cards in the response to those associated with this bank account ID, which is the facilitator-provided ID of the bank account
-                'external_customer_id'=>'',             //Filters the vaulted credit cards in the response to those associated with this externally-provided customer ID.
-                'total_required'=>''                    //Default true.Indicates whether the response returns the total_items and total_pages values.
-            );
-
-$returnArray = $PayPal->ListCreditCards($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/vault/StoreCreditCard.php b/templates/rest/vault/StoreCreditCard.php
deleted file mode 100644
index c1ebf867..00000000
--- a/templates/rest/vault/StoreCreditCard.php
+++ /dev/null
@@ -1,54 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-
-$creditCard = array(
-    'Type' => '',                   // Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-    'Number' => '',                 // Required.  Credit card number.  No spaces or punctuation.  
-    'ExpireMonth' => '',            // Required.  Credit card expiration Month.  Format is MM
-    'ExpireYear' => '',             // Required.  Credit card expiration year.  Format is YYYY
-    'Cvv2' => ''                    // Requirements determined by your PayPal account settings.  Security digits for credit card.                                     
-);
-$payerInfo = array(
-    'FirstName' => '',              // Required.  Payer's first name.
-    'LastName' => ''                // Required.  Payer's last name.
-);
-
-$billingAddress = array(
-    'line1' => '',                   // Required.  First street address.
-    'line2' => '',                   // Optional line 2 of the Address
-    'city' => '',                    // Required.  Name of City.    
-    'state' => '',                   // Required. 2 letter code for US states, and the equivalent for other countries..
-    'postal_code' => '',             // Required. postal code of your area.
-    'country_code' => '',            // 2 letter country code..   
-    'phone' => '',                   // Required.  Postal code of payer.
-);
-
-$optionalArray = array(
-    'MerchantId'=>'',                //The ID of the merchant for whom to list credit cards.
-    'ExternalCustomerId'=>'',        //The externally-provided ID of the customer for whom to list credit cards.
-    'ExternalCardId'=>''             //The externally-provided ID of the credit card.
-);
-
-$requestData = array(
-    'creditCard' => $creditCard,
-    'payerInfo' => $payerInfo,
-    'billingAddress' => $billingAddress,
-    'optionalArray' =>$optionalArray
-);
-
-$returnArray = $PayPal->StoreCreditCard($requestData);
-echo "
";
-print_r($returnArray);
diff --git a/templates/rest/vault/UpdateCreditCard.php b/templates/rest/vault/UpdateCreditCard.php
deleted file mode 100755
index f1ce23df..00000000
--- a/templates/rest/vault/UpdateCreditCard.php
+++ /dev/null
@@ -1,85 +0,0 @@
- $sandbox,
-    'ClientID' => $rest_client_id,
-    'ClientSecret' => $rest_client_secret,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-    'LogLevel' => $log_level
-);
-
-$PayPal = new \angelleye\PayPal\rest\vault\CreditCardAPI($configArray);
-$credit_card_id='';             //Required.The credit_card_id is the ID of the stored credit card. 
-
-$requestData = array(
-    array(
-        'operation' => '',                                   //Valid Values: ["add", "remove", "replace", test"]
-        'path'      => 'type',                              //Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-        'value'     => ''                                    //Value to add/remove/replace/move/copy/test
-    ),
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'number',                           // Required.  Credit card number.  No spaces or punctuation.  
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),    
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'expire_month',                     //Required.  Credit card expiration Month.  Format is MM 
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ), 
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'expire_year',                      // Required.  Credit card expiration year.  Format is YYYY
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),     
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace",  "test"]
-        'path'      => 'cvv2',                             // Requirements determined by your PayPal account settings.  Security digits for credit card.                                     
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),         
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'first_name',                       //Required.  Payer's first name.
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),  
-    array(
-        'operation' => 'replace',                                  //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'last_name',                        // Required.  Payer's last name.
-        'value'     => 'Mehta'                                   //Value to add/remove/replace/move/copy/test
-    ),  
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace", "test"]
-        'path'      => 'merchant_id',                      //The ID of the merchant for whom to list credit cards.
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),      
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace","test"]
-        'path'      => 'external_customer_id',             //The externally-provided ID of the customer for whom to list credit cards.
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),      
-    array(
-        'operation' => '',                                  //Valid Values: ["add", "remove", "replace","test"]
-        'path'      => 'external_card_id',                 //The externally-provided ID of the credit card.
-        'value'     => ''                                   //Value to add/remove/replace/move/copy/test
-    ),
-    array(
-        'operation' => '',                                   //Valid Values: ["add", "remove", "replace","test"]
-        'path'      => 'billing_address',                   //The externally-provided ID of the credit card.
-        'value'     => array(
-                            'line1' => '',                   // Required.  First street address.
-                            'line2' => '',                   // Optional line 2 of the Address
-                            'city'  => '',                    // Required.  Name of City.    
-                            'state' => '',                   // Required. 2 letter code for US states, and the equivalent for other countries..
-                            'postal_code' => '',             // Required. postal code of your area.
-                            'country_code' => '',            // 2 letter country code..   
-                            'phone' => '',                   // Required.  Postal code of payer.
-                        )                          
-    )
-);
-$returnArray = $PayPal->UpdateCreditCard($requestData,$credit_card_id);
-echo "
";
-print_r($returnArray);

From c0c89664dcfef5c29a5fc4df296bacbf491e6be4 Mon Sep 17 00:00:00 2001
From: Drew Angell 
Date: Sun, 20 Apr 2025 18:42:59 -0500
Subject: [PATCH 002/146] Updates gitignore, #219

---
 .gitignore | 63 ++++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 49 insertions(+), 14 deletions(-)

diff --git a/.gitignore b/.gitignore
index 07e9b058..18adfd91 100755
--- a/.gitignore
+++ b/.gitignore
@@ -1,16 +1,51 @@
-/_notes
-*/_notes
-/temp
-/test
-/includes/config.php
-/.settings
-!empty
-/.idea
+# General Ignored Files
+.DS_Store
+Thumbs.db
+
+# OS-generated files
+*.swp
+*.swo
+*.bak
+
+# PHPStorm and IDE-related files
+.idea/
+*.iml
+*.xml
+
+# Composer dependencies and related files
+/vendor/
 /composer.lock
-/vendor/*
-# exclude everything
-logs/*
-# exception to the rule
-!logs/.gitkeep 
-/includes
+
+# Node.js (if npm/yarn is used for assets)
+node_modules/
+
+# Temporary files
+*.log
+*.cache
+*.tmp
+/tmp/
+/logs/
+!logs/.gitkeep  # Exclude logs/.gitkeep, keep the directory structure
+
+# Private/sensitive files
+/includes/config.php
+/admin/config.php
+
+# Git merge conflict files
+*.orig
+
+# PHPUnit
+.phpunit.result.cache
+
+# Coverage and build
+/coverage/
+/build/
+
+# PHP-specific files
+.env
+.env.*       # Include files like .env.testing, .env.production
+/phpunit.xml
+/phpunit.xml.dist
+
+# Ignoring nbproject if NetBeans IDE is used
 /nbproject/private/
\ No newline at end of file

From 7de09d74d4dcd7eec25a65fbb25bff8b18beaff0 Mon Sep 17 00:00:00 2001
From: Drew Angell 
Date: Sun, 20 Apr 2025 19:24:15 -0500
Subject: [PATCH 003/146] Updates required PHP to 8.0.x+, #219

---
 composer.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/composer.json b/composer.json
index ebbe460a..35cffceb 100755
--- a/composer.json
+++ b/composer.json
@@ -13,7 +13,7 @@
         }
     ],
 	"require": {
-		"php": ">=5.3.0",
+		"php": ">=8.0.0",
 		"ext-curl": "*"
 	},
     "autoload": {

From 725d08c51068989ec6ae9c88989341f0dbcab6e0 Mon Sep 17 00:00:00 2001
From: Drew Angell 
Date: Sun, 20 Apr 2025 19:35:44 -0500
Subject: [PATCH 004/146] Adds missing var declarations for PHP 8
 compatibility, #219

---
 src/angelleye/PayPal/PayPal.php | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/angelleye/PayPal/PayPal.php b/src/angelleye/PayPal/PayPal.php
index 3d41eb94..6ff7f358 100755
--- a/src/angelleye/PayPal/PayPal.php
+++ b/src/angelleye/PayPal/PayPal.php
@@ -53,8 +53,20 @@ class PayPal
     var $PrintHeaders = '';
     var $LogResults = '';
     var $LogPath = '';
-	
-	/**
+    private string $api_url;
+    private string $api_key;
+    /**
+     * @var array|string[]
+     */
+    private array $allow_method;
+    protected string $NVPCredentials;
+    protected array $Countries;
+    protected array $States;
+    protected array $AVSCodes;
+    protected array $CVV2Codes;
+    protected array $CurrencyCodes;
+
+    /**
 	 * Constructor
 	 *
 	 * @access	public

From bb588beb56440357c8b1f40d4b0c024fd6659b80 Mon Sep 17 00:00:00 2001
From: Drew Angell 
Date: Sat, 13 Sep 2025 17:22:19 -0500
Subject: [PATCH 005/146] Adds .vscode/ to gitignore.

---
 .gitignore | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.gitignore b/.gitignore
index 18adfd91..0b66532b 100755
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,7 @@ Thumbs.db
 .idea/
 *.iml
 *.xml
+.vscode/
 
 # Composer dependencies and related files
 /vendor/

From 3044cb84872007fc32ff6a93ef1a376edd01e691 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 8 Oct 2025 19:14:31 +0530
Subject: [PATCH 006/146] NVP to REST Impelentation Started

---
 samples/config/config-sample.php             |   9 +
 src/angelleye/PayPal/Mapper/PayPalMapper.php | 321 +++++++++++++++++++
 src/angelleye/PayPal/PayPalREST.php          | 251 +++++++++++++++
 3 files changed, 581 insertions(+)
 create mode 100644 src/angelleye/PayPal/Mapper/PayPalMapper.php
 create mode 100644 src/angelleye/PayPal/PayPalREST.php

diff --git a/samples/config/config-sample.php b/samples/config/config-sample.php
index e108fb46..b8c2e99d 100755
--- a/samples/config/config-sample.php
+++ b/samples/config/config-sample.php
@@ -32,6 +32,15 @@
 	ini_set('display_errors', '1');	
 }
 
+/**
+ * PayPal API Mode and Version
+ * --------------------------
+ * Set which PayPal API to use: 'classic' for NVP/SOAP or 'rest' for REST API
+ * The library supports both Classic (NVP/SOAP) and REST APIs.
+ * Set this value to control which API your application will use.
+ */
+$paypal_api_mode = 'classic';  // Options: 'classic' or 'rest'
+
 /**
  * PayPal API Version
  * ------------------
diff --git a/src/angelleye/PayPal/Mapper/PayPalMapper.php b/src/angelleye/PayPal/Mapper/PayPalMapper.php
new file mode 100644
index 00000000..d7ddbd20
--- /dev/null
+++ b/src/angelleye/PayPal/Mapper/PayPalMapper.php
@@ -0,0 +1,321 @@
+ 'purchase_units[0].amount.value',
+        'CURRENCYCODE' => 'purchase_units[0].amount.currency_code',
+        
+        // URLs
+        'RETURNURL' => 'payment_source.paypal.experience_context.return_url',
+        'CANCELURL' => 'payment_source.paypal.experience_context.cancel_url',
+        
+        // Shipping
+        'NOSHIPPING' => 'payment_source.paypal.experience_context.shipping_preference',
+        'ADDROVERRIDE' => 'payment_source.paypal.experience_context.shipping_preference',
+        'SHIPTONAME' => 'purchase_units[0].shipping.name.full_name',
+        'SHIPTOSTREET' => 'purchase_units[0].shipping.address.address_line_1',
+        'SHIPTOSTREET2' => 'purchase_units[0].shipping.address.address_line_2',
+        'SHIPTOCITY' => 'purchase_units[0].shipping.address.admin_area_2',
+        'SHIPTOSTATE' => 'purchase_units[0].shipping.address.admin_area_1',
+        'SHIPTOZIP' => 'purchase_units[0].shipping.address.postal_code',
+        'SHIPTOCOUNTRYCODE' => 'purchase_units[0].shipping.address.country_code',
+        'SHIPTOPHONENUM' => 'purchase_units[0].shipping.phone.phone_number.national_number',
+        
+        // Experience
+        'BRANDNAME' => 'payment_source.paypal.experience_context.brand_name',
+        'LOCALECODE' => 'payment_source.paypal.experience_context.locale',
+        'LANDINGPAGE' => 'payment_source.paypal.experience_context.landing_page',
+        
+        // Order Details
+        'INVNUM' => 'purchase_units[0].invoice_id',
+        'CUSTOM' => 'purchase_units[0].custom_id',
+        'DESC' => 'purchase_units[0].description',
+        
+        // Amount Breakdown
+        'ITEMAMT' => 'purchase_units[0].amount.breakdown.item_total.value',
+        'SHIPPINGAMT' => 'purchase_units[0].amount.breakdown.shipping.value',
+        'HANDLINGAMT' => 'purchase_units[0].amount.breakdown.handling.value',
+        'TAXAMT' => 'purchase_units[0].amount.breakdown.tax_total.value',
+        'SHIPDISCAMT' => 'purchase_units[0].amount.breakdown.shipping_discount.value',
+        'INSURANCEAMT' => 'purchase_units[0].amount.breakdown.insurance.value'
+    ];
+
+    /**
+     * Maps classic NVP parameters to REST structure
+     */
+    public static function mapNvpToRest($params) {
+        $restData = [
+            'intent' => self::mapPaymentAction($params),
+            'purchase_units' => [
+                [
+                    'amount' => [
+                        'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
+                        'value' => $params['PAYMENTREQUEST_0_AMT'] ?? '0.00'
+                    ]
+                ]
+            ],
+            'payment_source' => [
+                'paypal' => [
+                    'experience_context' => self::mapExperienceContext($params)
+                ]
+            ]
+        ];
+
+        // Add items if present
+        if (self::hasLineItems($params)) {
+            $restData['purchase_units'][0]['items'] = self::mapLineItems($params);
+            $restData['purchase_units'][0]['amount']['breakdown'] = self::mapAmountBreakdown($params);
+        }
+
+        // Add shipping if present
+        if (self::hasShippingInfo($params)) {
+            $restData['purchase_units'][0]['shipping'] = self::mapShippingDetails($params);
+        }
+
+        // Add billing agreement details if present
+        if (self::hasBillingAgreement($params)) {
+            $restData = self::addBillingAgreementDetails($restData, $params);
+        }
+
+        return $restData;
+    }
+
+    /**
+     * Maps payment action to REST intent
+     */
+    protected static function mapPaymentAction($params) {
+        $action = $params['PAYMENTREQUEST_0_PAYMENTACTION'] ?? $params['PAYMENTACTION'] ?? 'Sale';
+        return strtolower($action) === 'authorization' ? 'AUTHORIZE' : 'CAPTURE';
+    }
+
+    /**
+     * Maps experience context parameters
+     */
+    protected static function mapExperienceContext($params) {
+        $context = [
+            'return_url' => $params['RETURNURL'] ?? '',
+            'cancel_url' => $params['CANCELURL'] ?? '',
+            'brand_name' => $params['BRANDNAME'] ?? null,
+            'locale' => $params['LOCALECODE'] ?? 'en-US',
+            'shipping_preference' => self::mapShippingPreference($params)
+        ];
+
+        if (isset($params['LANDINGPAGE'])) {
+            $context['landing_page'] = strtoupper($params['LANDINGPAGE']);
+        }
+
+        return array_filter($context, function($value) {
+            return $value !== null;
+        });
+    }
+
+    /**
+     * Maps shipping preference
+     */
+    protected static function mapShippingPreference($params) {
+        if (isset($params['NOSHIPPING']) && $params['NOSHIPPING'] === '1') {
+            return 'NO_SHIPPING';
+        }
+        if (isset($params['ADDROVERRIDE']) && $params['ADDROVERRIDE'] === '1') {
+            return 'SET_PROVIDED_ADDRESS';
+        }
+        return 'GET_FROM_FILE';
+    }
+
+    /**
+     * Maps line items from NVP to REST format
+     */
+    protected static function mapLineItems($params) {
+        $items = [];
+        $i = 0;
+        while (isset($params["L_PAYMENTREQUEST_0_NAME$i"])) {
+            $items[] = [
+                'name' => $params["L_PAYMENTREQUEST_0_NAME$i"],
+                'quantity' => $params["L_PAYMENTREQUEST_0_QTY$i"] ?? 1,
+                'unit_amount' => [
+                    'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
+                    'value' => $params["L_PAYMENTREQUEST_0_AMT$i"]
+                ],
+                'description' => $params["L_PAYMENTREQUEST_0_DESC$i"] ?? null,
+                'sku' => $params["L_PAYMENTREQUEST_0_NUMBER$i"] ?? null
+            ];
+            $i++;
+        }
+        return $items;
+    }
+
+    /**
+     * Maps amount breakdown
+     */
+    protected static function mapAmountBreakdown($params) {
+        $breakdown = [];
+        $mappings = [
+            'ITEMAMT' => 'item_total',
+            'SHIPPINGAMT' => 'shipping',
+            'HANDLINGAMT' => 'handling',
+            'TAXAMT' => 'tax_total',
+            'SHIPDISCAMT' => 'shipping_discount',
+            'INSURANCEAMT' => 'insurance'
+        ];
+
+        foreach ($mappings as $nvp => $rest) {
+            if (isset($params["PAYMENTREQUEST_0_$nvp"])) {
+                $breakdown[$rest] = [
+                    'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
+                    'value' => $params["PAYMENTREQUEST_0_$nvp"]
+                ];
+            }
+        }
+
+        return $breakdown;
+    }
+
+    /**
+     * Maps shipping details
+     */
+    protected static function mapShippingDetails($params) {
+        $shipping = [];
+
+        if (isset($params['PAYMENTREQUEST_0_SHIPTONAME'])) {
+            $shipping['name'] = [
+                'full_name' => $params['PAYMENTREQUEST_0_SHIPTONAME']
+            ];
+        }
+
+        if (self::hasShippingAddress($params)) {
+            $shipping['address'] = [
+                'address_line_1' => $params['PAYMENTREQUEST_0_SHIPTOSTREET'] ?? '',
+                'address_line_2' => $params['PAYMENTREQUEST_0_SHIPTOSTREET2'] ?? '',
+                'admin_area_2' => $params['PAYMENTREQUEST_0_SHIPTOCITY'] ?? '',
+                'admin_area_1' => $params['PAYMENTREQUEST_0_SHIPTOSTATE'] ?? '',
+                'postal_code' => $params['PAYMENTREQUEST_0_SHIPTOZIP'] ?? '',
+                'country_code' => $params['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] ?? ''
+            ];
+        }
+
+        if (isset($params['PAYMENTREQUEST_0_SHIPTOPHONENUM'])) {
+            $shipping['phone'] = [
+                'phone_number' => [
+                    'national_number' => $params['PAYMENTREQUEST_0_SHIPTOPHONENUM']
+                ]
+            ];
+        }
+
+        return $shipping;
+    }
+
+    /**
+     * Maps REST response to NVP format
+     */
+    public static function mapRestToNvp($response) {
+        $result = [
+            'TOKEN' => $response['id'],
+            'TIMESTAMP' => date('Y-m-d\TH:i:s\Z'),
+            'ACK' => 'Success'
+        ];
+
+        // Map approval URL
+        foreach ($response['links'] as $link) {
+            if ($link['rel'] === 'approve') {
+                $result['REDIRECTURL'] = $link['href'];
+                break;
+            }
+        }
+
+        // Map payment info if present
+        if (isset($response['purchase_units'][0]['payments'])) {
+            $payments = $response['purchase_units'][0]['payments'];
+            if (isset($payments['captures'][0])) {
+                $result['PAYMENTINFO_0_TRANSACTIONID'] = $payments['captures'][0]['id'];
+                $result['PAYMENTINFO_0_PAYMENTSTATUS'] = $payments['captures'][0]['status'];
+            } elseif (isset($payments['authorizations'][0])) {
+                $result['PAYMENTINFO_0_TRANSACTIONID'] = $payments['authorizations'][0]['id'];
+                $result['PAYMENTINFO_0_PAYMENTSTATUS'] = $payments['authorizations'][0]['status'];
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * Helper method to check if request has line items
+     */
+    protected static function hasLineItems($params) {
+        return isset($params['L_PAYMENTREQUEST_0_NAME0']);
+    }
+
+    /**
+     * Helper method to check if request has shipping info
+     */
+    protected static function hasShippingInfo($params) {
+        return isset($params['PAYMENTREQUEST_0_SHIPTONAME']) || 
+               self::hasShippingAddress($params);
+    }
+
+    /**
+     * Helper method to check if request has shipping address
+     */
+    protected static function hasShippingAddress($params) {
+        return isset($params['PAYMENTREQUEST_0_SHIPTOSTREET']) || 
+               isset($params['PAYMENTREQUEST_0_SHIPTOCITY']) ||
+               isset($params['PAYMENTREQUEST_0_SHIPTOSTATE']) ||
+               isset($params['PAYMENTREQUEST_0_SHIPTOZIP']) ||
+               isset($params['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE']);
+    }
+
+    /**
+     * Helper method to check if request has billing agreement
+     */
+    protected static function hasBillingAgreement($params) {
+        return isset($params['L_BILLINGTYPE0']);
+    }
+
+    /**
+     * Adds billing agreement details to REST payload
+     */
+    protected static function addBillingAgreementDetails($restData, $params) {
+        $restData['payment_source']['paypal']['attributes'] = [
+            'vault' => [
+                'store_in_vault' => 'ON_SUCCESS',
+                'usage_type' => 'MERCHANT',
+                'customer_type' => 'MERCHANT'
+            ]
+        ];
+        return $restData;
+    }
+
+    /**
+     * Validates required parameters for specific operations
+     */
+    public static function validateParams($params, $operation) {
+        $errors = [];
+        
+        switch ($operation) {
+            case 'SetExpressCheckout':
+                if (empty($params['RETURNURL'])) {
+                    $errors[] = 'RETURNURL is required';
+                }
+                if (empty($params['CANCELURL'])) {
+                    $errors[] = 'CANCELURL is required';
+                }
+                if (empty($params['PAYMENTREQUEST_0_AMT'])) {
+                    $errors[] = 'Amount is required';
+                }
+                break;
+            
+            case 'DoExpressCheckoutPayment':
+                if (empty($params['TOKEN'])) {
+                    $errors[] = 'TOKEN is required';
+                }
+                break;
+        }
+
+        return $errors;
+    }
+}
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
new file mode 100644
index 00000000..328f4352
--- /dev/null
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -0,0 +1,251 @@
+baseUrl = $this->mode === 'sandbox' 
+            ? 'https://api-m.sandbox.paypal.com'
+            : 'https://api-m.paypal.com';
+    }
+
+    /**
+     * Get OAuth 2.0 access token
+     */
+    protected function getAccessToken() {
+        // Return cached token if still valid
+        if ($this->accessToken && $this->tokenExpiry > time()) {
+            return $this->accessToken;
+        }
+
+        $url = $this->baseUrl . '/v1/oauth2/token';
+        $credentials = base64_encode(
+            $this->config['rest']['client_id'] . ':' . 
+            $this->config['rest']['client_secret']
+        );
+
+        $headers = [
+            'Authorization: Basic ' . $credentials,
+            'Content-Type: application/x-www-form-urlencoded',
+            'PayPal-Request-Id: ' . $this->generateRequestId()
+        ];
+
+        try {
+            $ch = curl_init();
+            curl_setopt_array($ch, [
+                CURLOPT_URL => $url,
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_POST => true,
+                CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
+                CURLOPT_HTTPHEADER => $headers,
+                CURLOPT_SSL_VERIFYPEER => true,
+                CURLOPT_SSL_VERIFYHOST => 2
+            ]);
+
+            $response = curl_exec($ch);
+            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+
+            if (curl_errno($ch)) {
+                throw new \Exception('cURL error: ' . curl_error($ch));
+            }
+
+            curl_close($ch);
+            $responseData = json_decode($response, true);
+
+            if ($httpCode >= 400) {
+                throw new \Exception(
+                    "OAuth Error: " . ($responseData['error_description'] ?? 'Unknown error')
+                );
+            }
+
+            $this->accessToken = $responseData['access_token'];
+            $this->tokenExpiry = time() + $responseData['expires_in'] - 60;
+            return $this->accessToken;
+
+        } catch (\Exception $e) {
+            $this->log->error('OAuth Error: ' . $e->getMessage());
+            throw $e;
+        }
+    }
+
+    /**
+     * Make REST API request with OAuth
+     */
+    protected function makeRestRequest($endpoint, $method, $data = null, $additionalHeaders = []) {
+        $headers = array_merge([
+            'Authorization: Bearer ' . $this->getAccessToken(),
+            'Content-Type: application/json',
+            'PayPal-Request-Id: ' . $this->generateRequestId()
+        ], $additionalHeaders);
+
+        try {
+            $ch = curl_init();
+            curl_setopt_array($ch, [
+                CURLOPT_URL => $this->baseUrl . $endpoint,
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_HTTPHEADER => $headers,
+                CURLOPT_SSL_VERIFYPEER => true,
+                CURLOPT_SSL_VERIFYHOST => 2
+            ]);
+
+            if ($method === 'POST') {
+                curl_setopt($ch, CURLOPT_POST, true);
+                if ($data) {
+                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+                }
+            }
+
+            $response = curl_exec($ch);
+            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+
+            if (curl_errno($ch)) {
+                throw new \Exception('cURL error: ' . curl_error($ch));
+            }
+
+            curl_close($ch);
+            $responseData = json_decode($response, true);
+
+            if ($httpCode >= 400) {
+                $this->handleRestError($responseData);
+            }
+
+            return $responseData;
+
+        } catch (\Exception $e) {
+            $this->log->error('REST API Error: ' . $e->getMessage());
+            throw $e;
+        }
+    }
+
+    /**
+     * Handle REST API errors
+     */
+    protected function handleRestError($response) {
+        $message = isset($response['message']) ? $response['message'] : 'Unknown error';
+        $debug_id = isset($response['debug_id']) ? $response['debug_id'] : '';
+        
+        $this->log->error("PayPal REST Error: $message (Debug ID: $debug_id)");
+        throw new \Exception("PayPal REST Error: $message (Debug ID: $debug_id)");
+    }
+
+    /**
+     * Generate unique request ID
+     */
+    protected function generateRequestId() {
+        return vsprintf('%s%s-%s-4000-8000-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));
+    }
+
+    /**
+     * SetExpressCheckout implementation using REST API
+     */
+    public function SetExpressCheckout($params) {
+        // Map classic params to REST format
+        $orderData = [
+            'intent' => isset($params['PAYMENTREQUEST_0_PAYMENTACTION']) && 
+                       $params['PAYMENTREQUEST_0_PAYMENTACTION'] === 'Authorization' 
+                       ? 'AUTHORIZE' : 'CAPTURE',
+            'purchase_units' => [
+                [
+                    'amount' => [
+                        'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
+                        'value' => $params['PAYMENTREQUEST_0_AMT'] ?? '0.00'
+                    ]
+                ]
+            ],
+            'payment_source' => [
+                'paypal' => [
+                    'experience_context' => [
+                        'return_url' => $params['RETURNURL'],
+                        'cancel_url' => $params['CANCELURL'],
+                        'brand_name' => $params['BRANDNAME'] ?? null,
+                        'locale' => $params['LOCALECODE'] ?? 'en-US',
+                        'shipping_preference' => $this->mapShippingPreference($params)
+                    ]
+                ]
+            ]
+        ];
+
+        // Add items if present
+        if (isset($params['L_PAYMENTREQUEST_0_NAME0'])) {
+            $orderData['purchase_units'][0]['items'] = $this->mapLineItems($params);
+            $orderData['purchase_units'][0]['amount']['breakdown'] = $this->mapAmountBreakdown($params);
+        }
+
+        // Add billing agreement details if present
+        if (isset($params['L_BILLINGTYPE0'])) {
+            $orderData = $this->addBillingAgreementDetails($orderData, $params);
+        }
+
+        $response = $this->makeRestRequest('/v2/checkout/orders', 'POST', $orderData);
+
+        // Return in classic format
+        return $this->formatOrderResponse($response);
+    }
+
+    /**
+     * Map shipping preference from classic to REST
+     */
+    protected function mapShippingPreference($params) {
+        if (isset($params['NOSHIPPING']) && $params['NOSHIPPING'] === '1') {
+            return 'NO_SHIPPING';
+        }
+        if (isset($params['ADDROVERRIDE']) && $params['ADDROVERRIDE'] === '1') {
+            return 'SET_PROVIDED_ADDRESS';
+        }
+        return 'GET_FROM_FILE';
+    }
+
+    /**
+     * Map line items from classic to REST
+     */
+    protected function mapLineItems($params) {
+        $items = [];
+        $i = 0;
+        while (isset($params["L_PAYMENTREQUEST_0_NAME$i"])) {
+            $items[] = [
+                'name' => $params["L_PAYMENTREQUEST_0_NAME$i"],
+                'quantity' => $params["L_PAYMENTREQUEST_0_QTY$i"] ?? 1,
+                'unit_amount' => [
+                    'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
+                    'value' => $params["L_PAYMENTREQUEST_0_AMT$i"]
+                ],
+                'description' => $params["L_PAYMENTREQUEST_0_DESC$i"] ?? null,
+                'sku' => $params["L_PAYMENTREQUEST_0_NUMBER$i"] ?? null
+            ];
+            $i++;
+        }
+        return $items;
+    }
+
+    /**
+     * Format REST response to match classic API
+     */
+    protected function formatOrderResponse($response) {
+        $result = [
+            'TOKEN' => $response['id'],
+            'TIMESTAMP' => date('Y-m-d\TH:i:s\Z'),
+            'ACK' => 'Success'
+        ];
+
+        foreach ($response['links'] as $link) {
+            if ($link['rel'] === 'approve') {
+                $result['REDIRECTURL'] = $link['href'];
+                break;
+            }
+        }
+
+        return $result;
+    }
+
+    // Additional methods would follow similar pattern...
+}
\ No newline at end of file

From 80ce7517d108a65281cd4fc1392d7417f66bef6a Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Thu, 9 Oct 2025 16:41:57 +0530
Subject: [PATCH 007/146] Set Flag for the NVP and REST Conversion

---
 samples/classic/GetBalance.php               |   19 +-
 samples/config/config-sample.php             |    2 +-
 src/angelleye/PayPal/Mapper/PayPalMapper.php |  321 --
 src/angelleye/PayPal/PayPal.php              | 3549 +-----------------
 src/angelleye/PayPal/PayPalREST.php          |  523 ++-
 5 files changed, 404 insertions(+), 4010 deletions(-)
 delete mode 100644 src/angelleye/PayPal/Mapper/PayPalMapper.php

diff --git a/samples/classic/GetBalance.php b/samples/classic/GetBalance.php
index 5fe2da8c..4c15ef1b 100644
--- a/samples/classic/GetBalance.php
+++ b/samples/classic/GetBalance.php
@@ -5,16 +5,17 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+		'Sandbox' => $sandbox,
+		'PayPalAPIMode' => $api_mode,
+		'APIUsername' => $api_username,
+		'APIPassword' => $api_password,
+		'APISignature' => $api_signature,
+		'PrintHeaders' => $print_headers,
+		'LogResults' => $log_results,
+		'LogPath' => $log_path,
+	);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $GBFields = array('returnallcurrencies' => '');
diff --git a/samples/config/config-sample.php b/samples/config/config-sample.php
index b8c2e99d..4f9dc980 100755
--- a/samples/config/config-sample.php
+++ b/samples/config/config-sample.php
@@ -39,7 +39,7 @@
  * The library supports both Classic (NVP/SOAP) and REST APIs.
  * Set this value to control which API your application will use.
  */
-$paypal_api_mode = 'classic';  // Options: 'classic' or 'rest'
+$api_mode = 'classic';  // Options: 'classic' or 'rest'
 
 /**
  * PayPal API Version
diff --git a/src/angelleye/PayPal/Mapper/PayPalMapper.php b/src/angelleye/PayPal/Mapper/PayPalMapper.php
deleted file mode 100644
index d7ddbd20..00000000
--- a/src/angelleye/PayPal/Mapper/PayPalMapper.php
+++ /dev/null
@@ -1,321 +0,0 @@
- 'purchase_units[0].amount.value',
-        'CURRENCYCODE' => 'purchase_units[0].amount.currency_code',
-        
-        // URLs
-        'RETURNURL' => 'payment_source.paypal.experience_context.return_url',
-        'CANCELURL' => 'payment_source.paypal.experience_context.cancel_url',
-        
-        // Shipping
-        'NOSHIPPING' => 'payment_source.paypal.experience_context.shipping_preference',
-        'ADDROVERRIDE' => 'payment_source.paypal.experience_context.shipping_preference',
-        'SHIPTONAME' => 'purchase_units[0].shipping.name.full_name',
-        'SHIPTOSTREET' => 'purchase_units[0].shipping.address.address_line_1',
-        'SHIPTOSTREET2' => 'purchase_units[0].shipping.address.address_line_2',
-        'SHIPTOCITY' => 'purchase_units[0].shipping.address.admin_area_2',
-        'SHIPTOSTATE' => 'purchase_units[0].shipping.address.admin_area_1',
-        'SHIPTOZIP' => 'purchase_units[0].shipping.address.postal_code',
-        'SHIPTOCOUNTRYCODE' => 'purchase_units[0].shipping.address.country_code',
-        'SHIPTOPHONENUM' => 'purchase_units[0].shipping.phone.phone_number.national_number',
-        
-        // Experience
-        'BRANDNAME' => 'payment_source.paypal.experience_context.brand_name',
-        'LOCALECODE' => 'payment_source.paypal.experience_context.locale',
-        'LANDINGPAGE' => 'payment_source.paypal.experience_context.landing_page',
-        
-        // Order Details
-        'INVNUM' => 'purchase_units[0].invoice_id',
-        'CUSTOM' => 'purchase_units[0].custom_id',
-        'DESC' => 'purchase_units[0].description',
-        
-        // Amount Breakdown
-        'ITEMAMT' => 'purchase_units[0].amount.breakdown.item_total.value',
-        'SHIPPINGAMT' => 'purchase_units[0].amount.breakdown.shipping.value',
-        'HANDLINGAMT' => 'purchase_units[0].amount.breakdown.handling.value',
-        'TAXAMT' => 'purchase_units[0].amount.breakdown.tax_total.value',
-        'SHIPDISCAMT' => 'purchase_units[0].amount.breakdown.shipping_discount.value',
-        'INSURANCEAMT' => 'purchase_units[0].amount.breakdown.insurance.value'
-    ];
-
-    /**
-     * Maps classic NVP parameters to REST structure
-     */
-    public static function mapNvpToRest($params) {
-        $restData = [
-            'intent' => self::mapPaymentAction($params),
-            'purchase_units' => [
-                [
-                    'amount' => [
-                        'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
-                        'value' => $params['PAYMENTREQUEST_0_AMT'] ?? '0.00'
-                    ]
-                ]
-            ],
-            'payment_source' => [
-                'paypal' => [
-                    'experience_context' => self::mapExperienceContext($params)
-                ]
-            ]
-        ];
-
-        // Add items if present
-        if (self::hasLineItems($params)) {
-            $restData['purchase_units'][0]['items'] = self::mapLineItems($params);
-            $restData['purchase_units'][0]['amount']['breakdown'] = self::mapAmountBreakdown($params);
-        }
-
-        // Add shipping if present
-        if (self::hasShippingInfo($params)) {
-            $restData['purchase_units'][0]['shipping'] = self::mapShippingDetails($params);
-        }
-
-        // Add billing agreement details if present
-        if (self::hasBillingAgreement($params)) {
-            $restData = self::addBillingAgreementDetails($restData, $params);
-        }
-
-        return $restData;
-    }
-
-    /**
-     * Maps payment action to REST intent
-     */
-    protected static function mapPaymentAction($params) {
-        $action = $params['PAYMENTREQUEST_0_PAYMENTACTION'] ?? $params['PAYMENTACTION'] ?? 'Sale';
-        return strtolower($action) === 'authorization' ? 'AUTHORIZE' : 'CAPTURE';
-    }
-
-    /**
-     * Maps experience context parameters
-     */
-    protected static function mapExperienceContext($params) {
-        $context = [
-            'return_url' => $params['RETURNURL'] ?? '',
-            'cancel_url' => $params['CANCELURL'] ?? '',
-            'brand_name' => $params['BRANDNAME'] ?? null,
-            'locale' => $params['LOCALECODE'] ?? 'en-US',
-            'shipping_preference' => self::mapShippingPreference($params)
-        ];
-
-        if (isset($params['LANDINGPAGE'])) {
-            $context['landing_page'] = strtoupper($params['LANDINGPAGE']);
-        }
-
-        return array_filter($context, function($value) {
-            return $value !== null;
-        });
-    }
-
-    /**
-     * Maps shipping preference
-     */
-    protected static function mapShippingPreference($params) {
-        if (isset($params['NOSHIPPING']) && $params['NOSHIPPING'] === '1') {
-            return 'NO_SHIPPING';
-        }
-        if (isset($params['ADDROVERRIDE']) && $params['ADDROVERRIDE'] === '1') {
-            return 'SET_PROVIDED_ADDRESS';
-        }
-        return 'GET_FROM_FILE';
-    }
-
-    /**
-     * Maps line items from NVP to REST format
-     */
-    protected static function mapLineItems($params) {
-        $items = [];
-        $i = 0;
-        while (isset($params["L_PAYMENTREQUEST_0_NAME$i"])) {
-            $items[] = [
-                'name' => $params["L_PAYMENTREQUEST_0_NAME$i"],
-                'quantity' => $params["L_PAYMENTREQUEST_0_QTY$i"] ?? 1,
-                'unit_amount' => [
-                    'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
-                    'value' => $params["L_PAYMENTREQUEST_0_AMT$i"]
-                ],
-                'description' => $params["L_PAYMENTREQUEST_0_DESC$i"] ?? null,
-                'sku' => $params["L_PAYMENTREQUEST_0_NUMBER$i"] ?? null
-            ];
-            $i++;
-        }
-        return $items;
-    }
-
-    /**
-     * Maps amount breakdown
-     */
-    protected static function mapAmountBreakdown($params) {
-        $breakdown = [];
-        $mappings = [
-            'ITEMAMT' => 'item_total',
-            'SHIPPINGAMT' => 'shipping',
-            'HANDLINGAMT' => 'handling',
-            'TAXAMT' => 'tax_total',
-            'SHIPDISCAMT' => 'shipping_discount',
-            'INSURANCEAMT' => 'insurance'
-        ];
-
-        foreach ($mappings as $nvp => $rest) {
-            if (isset($params["PAYMENTREQUEST_0_$nvp"])) {
-                $breakdown[$rest] = [
-                    'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD',
-                    'value' => $params["PAYMENTREQUEST_0_$nvp"]
-                ];
-            }
-        }
-
-        return $breakdown;
-    }
-
-    /**
-     * Maps shipping details
-     */
-    protected static function mapShippingDetails($params) {
-        $shipping = [];
-
-        if (isset($params['PAYMENTREQUEST_0_SHIPTONAME'])) {
-            $shipping['name'] = [
-                'full_name' => $params['PAYMENTREQUEST_0_SHIPTONAME']
-            ];
-        }
-
-        if (self::hasShippingAddress($params)) {
-            $shipping['address'] = [
-                'address_line_1' => $params['PAYMENTREQUEST_0_SHIPTOSTREET'] ?? '',
-                'address_line_2' => $params['PAYMENTREQUEST_0_SHIPTOSTREET2'] ?? '',
-                'admin_area_2' => $params['PAYMENTREQUEST_0_SHIPTOCITY'] ?? '',
-                'admin_area_1' => $params['PAYMENTREQUEST_0_SHIPTOSTATE'] ?? '',
-                'postal_code' => $params['PAYMENTREQUEST_0_SHIPTOZIP'] ?? '',
-                'country_code' => $params['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] ?? ''
-            ];
-        }
-
-        if (isset($params['PAYMENTREQUEST_0_SHIPTOPHONENUM'])) {
-            $shipping['phone'] = [
-                'phone_number' => [
-                    'national_number' => $params['PAYMENTREQUEST_0_SHIPTOPHONENUM']
-                ]
-            ];
-        }
-
-        return $shipping;
-    }
-
-    /**
-     * Maps REST response to NVP format
-     */
-    public static function mapRestToNvp($response) {
-        $result = [
-            'TOKEN' => $response['id'],
-            'TIMESTAMP' => date('Y-m-d\TH:i:s\Z'),
-            'ACK' => 'Success'
-        ];
-
-        // Map approval URL
-        foreach ($response['links'] as $link) {
-            if ($link['rel'] === 'approve') {
-                $result['REDIRECTURL'] = $link['href'];
-                break;
-            }
-        }
-
-        // Map payment info if present
-        if (isset($response['purchase_units'][0]['payments'])) {
-            $payments = $response['purchase_units'][0]['payments'];
-            if (isset($payments['captures'][0])) {
-                $result['PAYMENTINFO_0_TRANSACTIONID'] = $payments['captures'][0]['id'];
-                $result['PAYMENTINFO_0_PAYMENTSTATUS'] = $payments['captures'][0]['status'];
-            } elseif (isset($payments['authorizations'][0])) {
-                $result['PAYMENTINFO_0_TRANSACTIONID'] = $payments['authorizations'][0]['id'];
-                $result['PAYMENTINFO_0_PAYMENTSTATUS'] = $payments['authorizations'][0]['status'];
-            }
-        }
-
-        return $result;
-    }
-
-    /**
-     * Helper method to check if request has line items
-     */
-    protected static function hasLineItems($params) {
-        return isset($params['L_PAYMENTREQUEST_0_NAME0']);
-    }
-
-    /**
-     * Helper method to check if request has shipping info
-     */
-    protected static function hasShippingInfo($params) {
-        return isset($params['PAYMENTREQUEST_0_SHIPTONAME']) || 
-               self::hasShippingAddress($params);
-    }
-
-    /**
-     * Helper method to check if request has shipping address
-     */
-    protected static function hasShippingAddress($params) {
-        return isset($params['PAYMENTREQUEST_0_SHIPTOSTREET']) || 
-               isset($params['PAYMENTREQUEST_0_SHIPTOCITY']) ||
-               isset($params['PAYMENTREQUEST_0_SHIPTOSTATE']) ||
-               isset($params['PAYMENTREQUEST_0_SHIPTOZIP']) ||
-               isset($params['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE']);
-    }
-
-    /**
-     * Helper method to check if request has billing agreement
-     */
-    protected static function hasBillingAgreement($params) {
-        return isset($params['L_BILLINGTYPE0']);
-    }
-
-    /**
-     * Adds billing agreement details to REST payload
-     */
-    protected static function addBillingAgreementDetails($restData, $params) {
-        $restData['payment_source']['paypal']['attributes'] = [
-            'vault' => [
-                'store_in_vault' => 'ON_SUCCESS',
-                'usage_type' => 'MERCHANT',
-                'customer_type' => 'MERCHANT'
-            ]
-        ];
-        return $restData;
-    }
-
-    /**
-     * Validates required parameters for specific operations
-     */
-    public static function validateParams($params, $operation) {
-        $errors = [];
-        
-        switch ($operation) {
-            case 'SetExpressCheckout':
-                if (empty($params['RETURNURL'])) {
-                    $errors[] = 'RETURNURL is required';
-                }
-                if (empty($params['CANCELURL'])) {
-                    $errors[] = 'CANCELURL is required';
-                }
-                if (empty($params['PAYMENTREQUEST_0_AMT'])) {
-                    $errors[] = 'Amount is required';
-                }
-                break;
-            
-            case 'DoExpressCheckoutPayment':
-                if (empty($params['TOKEN'])) {
-                    $errors[] = 'TOKEN is required';
-                }
-                break;
-        }
-
-        return $errors;
-    }
-}
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPal.php b/src/angelleye/PayPal/PayPal.php
index 6ff7f358..590aca94 100755
--- a/src/angelleye/PayPal/PayPal.php
+++ b/src/angelleye/PayPal/PayPal.php
@@ -1,8 +1,11 @@
-
  *
- * @package			paypal-php-library
- * @author			Andrew Angell 
- * @link			https://github.com/angelleye/paypal-php-library/
- * @website			http://www.angelleye.com
+ * @package         paypal-php-library
+ * @author          Andrew Angell 
+ * @link            https://github.com/angelleye/paypal-php-library/
+ * @website         http://www.angelleye.com
  * @support         http://www.angelleye.com/product/premium-support/
- * @version			v3.0.5
+ * @version         v3.0.5
  * @filesource
 */
 
 /**
- * Primary PayPal Class
+ * Primary Abstract PayPal Class
  *
- * This is the parent PayPal class that all child classes extend.  
+ * This is the parent PayPal class that all child classes extend.
  *
- * @package 		paypal-php-library
- * @author			Andrew Angell 
+ * @package         paypal-php-library
+ * @author          Andrew Angell 
  */
 class PayPal
 {
+    protected array $config;
+    protected string $mode;
+    protected string $payPalAPIMode; // 'classic' or 'rest'
+    protected bool $Sandbox = true;
+    protected ?string $LogPath = null;
 
-	var $APIUsername = '';
-	var $APIPassword = '';
-	var $APISignature = '';
-	var $APISubject = '';
-	var $APIVersion = '';
-	var $APIButtonSource = '';
-	var $APIMode = '';
-	var $EndPointURL = '';
-	var $Sandbox = '';
-	var $PathToCertKeyPEM = '';
-	var $SSL = '';
-    var $PrintHeaders = '';
-    var $LogResults = '';
-    var $LogPath = '';
-    private string $api_url;
-    private string $api_key;
-    /**
-     * @var array|string[]
-     */
-    private array $allow_method;
-    protected string $NVPCredentials;
-    protected array $Countries;
-    protected array $States;
-    protected array $AVSCodes;
-    protected array $CVV2Codes;
-    protected array $CurrencyCodes;
-
-    /**
-	 * Constructor
-	 *
-	 * @access	public
-	 * @param	mixed[]	$DataArray	Array structure providing config data
-	 * @return	void
-	 */
-	function __construct($DataArray)
-	{		
-		if(isset($DataArray['Sandbox']))
-		{
-			$this->Sandbox = $DataArray['Sandbox'];
-		
-		}
-		else
-		{
-			$this->Sandbox = true;
-		}
-			
-		$this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0';
-		$this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature';
-		$this->APIButtonSource = '';
-		$this->PathToCertKeyPEM = '/path/to/cert/pem.txt';
-		$this->SSL = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? true : false;
-		$this->APISubject = isset($DataArray['APISubject']) ? $DataArray['APISubject'] : '';
-        $this->PrintHeaders = isset($DataArray['PrintHeaders']) ? $DataArray['PrintHeaders'] : false;
-        $this->LogResults = isset($DataArray['LogResults']) ? $DataArray['LogResults'] : false;
-        $this->LogPath = isset($DataArray['LogPath']) ? $DataArray['LogPath'] : '/logs/';
-        $this->api_url = 'https://gtctgyk7fh.execute-api.us-east-2.amazonaws.com/default/PayPalPaymentsTracker';
-        $this->api_key = 'srGiuJFpDO4W7YCDXF56g2c9nT1JhlURVGqYD7oa';
-        $this->allow_method = array('DoExpressCheckoutPayment', 'DoDirectPayment', 'DoCapture', 'ProcessTransaction', 'PayPal_Rest');
-
-		if($this->Sandbox)
-		{
-			// Show Errors
-			error_reporting(E_ALL);
-			ini_set('display_errors', '1');
-		
-			# Sandbox
-			$this->APIUsername = isset($DataArray['APIUsername']) && $DataArray['APIUsername'] != '' ? $DataArray['APIUsername'] : '';
-			$this->APIPassword = isset($DataArray['APIPassword']) && $DataArray['APIPassword'] != '' ? $DataArray['APIPassword'] : '';
-			$this->APISignature = isset($DataArray['APISignature']) && $DataArray['APISignature'] != '' ? $DataArray['APISignature'] : '';
-			$this->EndPointURL = isset($DataArray['EndPointURL']) && $DataArray['EndPointURL'] != '' ? $DataArray['EndPointURL'] : 'https://api-3t.sandbox.paypal.com/nvp';	
-		}
-		else
-		{
-			$this->APIUsername = isset($DataArray['APIUsername']) && $DataArray['APIUsername'] != '' ? $DataArray['APIUsername'] : '';
-			$this->APIPassword = isset($DataArray['APIPassword']) && $DataArray['APIPassword'] != '' ? $DataArray['APIPassword'] : '';
-			$this->APISignature = isset($DataArray['APISignature']) && $DataArray['APISignature'] != '' ? $DataArray['APISignature'] : '';
-			$this->EndPointURL = isset($DataArray['EndPointURL']) && $DataArray['EndPointURL'] != ''  ? $DataArray['EndPointURL'] : 'https://api-3t.paypal.com/nvp';
-		}
-				
-		// Create the NVP credentials string which is required in all calls.
-		$this->NVPCredentials = 'USER=' . $this->APIUsername . '&PWD=' . $this->APIPassword . '&VERSION=' . $this->APIVersion . '&BUTTONSOURCE=' . $this->APIButtonSource;
-		$this->NVPCredentials .= $this->APISubject != '' ? '&SUBJECT=' . $this->APISubject : '';
-		$this->NVPCredentials .= $this->APIMode == 'Signature' ? '&SIGNATURE=' . $this->APISignature : '';
-		
-		$this->Countries = array(
-							'Afghanistan' => 'AF',
-							'ÌÉland Islands' => 'AX',
-							'Albania' => 'AL',
-							'Algeria' => 'DZ',
-							'American Samoa' => 'AS',
-							'Andorra' => 'AD',
-							'Angola' => 'AO',
-							'Anguilla' => 'AI',
-							'Antarctica' => 'AQ',
-							'Antigua and Barbuda' => 'AG',
-							'Argentina' => 'AR',
-							'Armenia' => 'AM',
-							'Aruba' => 'AW',
-							'Australia' => 'AU',
-							'Austria' => 'AT',
-							'Azerbaijan' => 'AZ',
-							'Bahamas' => 'BS',
-							'Bahrain' => 'BH',
-							'Bangladesh' => 'BD',
-							'Barbados' => 'BB',
-							'Belarus' => 'BY',
-							'Belgium' => 'BE',
-							'Belize' => 'BZ',
-							'Benin' => 'BJ',
-							'Bermuda' => 'BM',
-							'Bhutan' => 'BT',
-							'Bolivia' => 'BO',
-							'Bosnia and Herzegovina' => 'BA',
-							'Botswana' => 'BW',
-							'Bouvet Island' => 'BV',
-							'Brazil' => 'BR',
-							'British Indian Ocean Territory' => 'IO',
-							'Brunei Darussalam' => 'BN',
-							'Bulgaria' => 'BG',
-							'Burkina Faso' => 'BF',
-							'Burundi' => 'BI',
-							'Cambodia' => 'KH',
-							'Cameroon' => 'CM',
-							'Canada' => 'CA',
-							'Cape Verde' => 'CV',
-							'Cayman Islands' => 'KY',
-							'Central African Republic' => 'CF',
-							'Chad' => 'TD',
-							'Chile' => 'CL',
-							'China' => 'CN',
-							'Christmas Island' => 'CX',
-							'Cocos (Keeling) Islands' => 'CC',
-							'Colombia' => 'CO',
-							'Comoros' => 'KM',
-							'Congo' => 'CG',
-							'Congo, The Democratic Republic of the' => 'CD',
-							'Cook Islands' => 'CK',
-							'Costa Rica' => 'CR',
-							"Cote D'Ivoire" => 'CI',
-							'Croatia' => 'HR',
-							'Cuba' => 'CU',
-							'Cyprus' => 'CY',
-							'Czech Republic' => 'CZ',
-							'Denmark' => 'DK',
-							'Djibouti' => 'DJ',
-							'Dominica' => 'DM',
-							'Dominican Republic' => 'DO',
-							'Ecuador' => 'EC',
-							'Egypt' => 'EG',
-							'El Salvador' => 'SV',
-							'Equatorial Guinea' => 'GQ',
-							'Eritrea' => 'ER',
-							'Estonia' => 'EE',
-							'Ethiopia' => 'ET',
-							'Falkland Islands (Malvinas)' => 'FK',
-							'Faroe Islands' => 'FO',
-							'Fiji' => 'FJ',
-							'Finland' => 'FI',
-							'France' => 'FR',
-							'French Guiana' => 'GF',
-							'French Polynesia' => 'PF',
-							'French Southern Territories' => 'TF',
-							'Gabon' => 'GA',
-							'Gambia' => 'GM',
-							'Georgia' => 'GE',
-							'Germany' => 'DE',
-							'Ghana' => 'GH',
-							'Gibraltar' => 'GI',
-							'Greece' => 'GR',
-							'Greenland' => 'GL',
-							'Grenada' => 'GD',
-							'Guadeloupe' => 'GP',
-							'Guam' => 'GU',
-							'Guatemala' => 'GT',
-							'Guernsey' => 'GG',
-							'Guinea' => 'GN',
-							'Guinea-Bissau' => 'GW',
-							'Guyana' => 'GY',
-							'Haiti' => 'HT',
-							'Heard Island and McDonald Islands' => 'HM',
-							'Holy See (Vatican City State)' => 'VA',
-							'Honduras' => 'HN',
-							'Hong Kong' => 'HK',
-							'Hungary' => 'HU',
-							'Iceland' => 'IS',
-							'India' => 'IN',
-							'Indonesia' => 'ID',
-							'Iran, Islamic Republic of' => 'IR',
-							'Iraq' => 'IQ',
-							'Ireland' => 'IE',
-							'Isle of Man' => 'IM',
-							'Israel' => 'IL',
-							'Italy' => 'IT',
-							'Jamaica' => 'JM',
-							'Japan' => 'JP',
-							'Jersey' => 'JE',
-							'Jordan' => 'JO',
-							'Kazakhstan' => 'KZ',
-							'Kenya' => 'KE',
-							'Kiribati' => 'KI',
-							"Korea, Democratic People's Republic of" => 'KP',
-							'Korea, Republic of' => 'KR',
-							'Kuwait' => 'KW',
-							'Kyrgyzstan' => 'KG',
-							"Laos People's Democratic Republic" => 'LA',
-							'Latvia' => 'LV',
-							'Lebanon' => 'LB',
-							'Lesotho' => 'LS',
-							'Liberia' => 'LR',
-							'Libyan Arab Jamahiriya' => 'LY',
-							'Liechtenstein' => 'LI',
-							'Lithuania' => 'LT',
-							'Luxembourg' => 'LU',
-							'Macao' => 'MO',
-							'Macedonia, The former Yugoslav Republic of' => 'MK',
-							'Madagascar' => 'MG',
-							'Malawi' => 'MW',
-							'Malaysia' => 'MY',
-							'Maldives' => 'MV',
-							'Mali' => 'ML',
-							'Malta' => 'MT',
-							'Marshall Islands' => 'MH',
-							'Martinique' => 'MQ',
-							'Mauritania' => 'MR',
-							'Mauritius' => 'MU',
-							'Mayotte' => 'YT',
-							'Mexico' => 'MX',
-							'Micronesia, Federated States of' => 'FM',
-							'Moldova, Republic of' => 'MD',
-							'Monaco' => 'MC',
-							'Mongolia' => 'MN',
-							'Montserrat' => 'MS',
-							'Morocco' => 'MA',
-							'Mozambique' => 'MZ',
-							'Myanmar' => 'MM',
-							'Namibia' => 'NA',
-							'Nauru' => 'NR',
-							'Nepal' => 'NP',
-							'Netherlands' => 'NL',
-							'Netherlands Antilles' => 'AN',
-							'New Caledonia' => 'NC',
-							'New Zealand' => 'NZ',
-							'Nicaragua' => 'NI',
-							'Niger' => 'NE',
-							'Nigeria' => 'NG',
-							'Niue' => 'NU',
-							'Norfolk Island' => 'NF',
-							'Northern Mariana Islands' => 'MP',
-							'Norway' => 'NO',
-							'Oman' => 'OM',
-							'Pakistan' => 'PK',
-							'Palau' => 'PW',
-							'Palestinian Territory, Occupied' => 'PS',
-							'Panama' => 'PA',
-							'Papua New Guinea' => 'PG',
-							'Paraguay' => 'PY',
-							'Peru' => 'PE',
-							'Philippines' => 'PH',
-							'Pitcairn' => 'PN',
-							'Poland' => 'PL',
-							'Portugal' => 'PT',
-							'Puerto Rico' => 'PR',
-							'Qatar' => 'QA',
-							'Reunion' => 'RE',
-							'Romania' => 'RO',
-							'Russian Federation' => 'RU',
-							'Rwanda' => 'RW',
-							'Saint Helena' => 'SH',
-							'Saint Kitts and Nevis' => 'KN',
-							'Saint Lucia' => 'LC',
-							'Saint Pierre and Miquelon' => 'PM',
-							'Saint Vincent and the Grenadines' => 'VC',
-							'Samoa' => 'WS',
-							'San Marino' => 'SM',
-							'Sao Tome and Principe' => 'ST',
-							'Saudi Arabia' => 'SA',
-							'Senegal' => 'SN',
-							'Serbia and Montenegro' => 'CS',
-							'Seychelles' => 'SC',
-							'Sierra Leone' => 'SL',
-							'Singapore' => 'SG',
-							'Slovakia' => 'SK',
-							'Slovenia' => 'SI',
-							'Solomon Islands' => 'SB',
-							'Somalia' => 'SO',
-							'South Africa' => 'ZA',
-							'South Georgia and the South Sandwich Islands' => 'GS',
-							'Spain' => 'ES',
-							'Sri Lanka' => 'LK',
-							'Sudan' => 'SD',
-							'Suriname' => 'SR',
-							'SValbard and Jan Mayen' => 'SJ',
-							'Swaziland' => 'SZ',
-							'Sweden' => 'SE',
-							'Switzerland' => 'CH',
-							'Syrian Arab Republic' => 'SY',
-							'Taiwan, Province of China' => 'TW',
-							'Tajikistan' => 'TJ',
-							'Tanzania, United Republic of' => 'TZ',
-							'Thailand' => 'TH',
-							'Timor-Leste' => 'TL',
-							'Togo' => 'TG',
-							'Tokelau' => 'TK',
-							'Tonga' => 'TO',
-							'Trinidad and Tobago' => 'TT',
-							'Tunisia' => 'TN',
-							'Turkey' => 'TR',
-							'Turkmenistan' => 'TM',
-							'Turks and Caicos Islands' => 'TC',
-							'Tuvalu' => 'TV',
-							'Uganda' => 'UG',
-							'Ukraine' => 'UA',
-							'United Arab Emirates' => 'AE',
-							'United Kingdom' => 'GB',
-							'United States' => 'US',
-							'United States Minor Outlying Islands' => 'UM',
-							'Uruguay' => 'UY',
-							'Uzbekistan' => 'UZ',
-							'Vanuatu' => 'VU',
-							'Venezuela' => 'VE',
-							'Viet Nam' => 'VN',
-							'Virgin Islands, British' => 'VG',
-							'Virgin Islands, U.S.' => 'VI',
-							'Wallis and Futuna' => 'WF',
-							'Western Sahara' => 'EH',
-							'Yemen' => 'YE',
-							'Zambia' => 'ZM',
-							'Zimbabwe' => 'ZW');
-							
-		$this->States = array(
-						'Alberta' => 'AB',
-						'British Columbia' => 'BC',
-						'Manitoba' => 'MB',
-						'New Brunswick' => 'NB',
-						'Newfoundland and Labrador' => 'NF',
-						'Northwest Territories' => 'NT',
-						'Nova Scotia' => 'NS',
-						'Nunavut' => 'NU',
-						'Ontario' => 'ON',
-						'Prince Edward Island' => 'PE',
-						'Quebec' => 'QC',
-						'Saskatchewan' => 'SK',
-						'Yukon' => 'YK',
-						'Alabama' => 'AL',
-						'Alaska' => 'AK',
-						'American Samoa' => 'AS',
-						'Arizona' => 'AZ',
-						'Arkansas' => 'AR',
-						'California' => 'CA',
-						'Colorado' => 'CO',
-						'Connecticut' => 'CT',
-						'Delaware' => 'DE',
-						'District of Columbia' => 'DC',
-						'Federated States of Micronesia' => 'FM',
-						'Florida' => 'FL',
-						'Georgia' => 'GA',
-						'Guam' => 'GU',
-						'Hawaii' => 'HI',
-						'Idaho' => 'ID',
-						'Illinois' => 'IL',
-						'Indiana' => 'IN',
-						'Iowa' => 'IA',
-						'Kansas' => 'KS',
-						'Kentucky' => 'KY',
-						'Louisiana' => 'LA',
-						'Maine' => 'ME',
-						'Marshall Islands' => 'MH',
-						'Maryland' => 'MD',
-						'Massachusetts' => 'MA',
-						'Michigan' => 'MI',
-						'Minnesota' => 'MN',
-						'Mississippi' => 'MS',
-						'Missouri' => 'MO',
-						'Montana' => 'MT',
-						'Nebraska' => 'NE',
-						'Nevada' => 'NV',
-						'New Hampshire' => 'NH',
-						'New Jersey' => 'NJ',
-						'New Mexico' => 'NM',
-						'New York' => 'NY',
-						'North Carolina' => 'NC',
-						'North Dakota' => 'ND',
-						'Northern Mariana Islands' => 'MP',
-						'Ohio' => 'OH',
-						'Oklahoma' => 'OK',
-						'Oregon' => 'OR',
-						'Palau' => 'PW',
-						'Pennsylvania' => 'PA',
-						'Puerto Rico' => 'PR',
-						'Rhode Island' => 'RI',
-						'South Carolina' => 'SC',
-						'South Dakota' => 'SD',
-						'Tennessee' => 'TN',
-						'Texas' => 'TX',
-						'Utah' => 'UT',
-						'Vermont' => 'VT',
-						'Virgin Islands' => 'VI',
-						'Virginia' => 'VA',
-						'Washington' => 'WA',
-						'West Virginia' => 'WV',
-						'Wisconsin' => 'WI',
-						'Wyoming' => 'WY',
-						'Armed Forces Americas' => 'AA',
-						'Armed Forces' => 'AE',
-						'Armed Forces Pacific' => 'AP');
-						
-		$this->AVSCodes = array("A" => "Address Matches Only (No ZIP)", 
-								  "B" => "Address Matches Only (No ZIP)", 
-								  "C" => "This tranaction was declined.", 
-								  "D" => "Address and Postal Code Match", 
-								  "E" => "This transaction was declined.", 
-								  "F" => "Address and Postal Code Match", 
-								  "G" => "Global Unavailable - N/A", 
-								  "I" => "International Unavailable - N/A", 
-								  "N" => "None - Transaction was declined.", 
-								  "P" => "Postal Code Match Only (No Address)", 
-								  "R" => "Retry - N/A", 
-								  "S" => "Service not supported - N/A", 
-								  "U" => "Unavailable - N/A", 
-								  "W" => "Nine-Digit ZIP Code Match (No Address)", 
-								  "X" => "Exact Match - Address and Nine-Digit ZIP", 
-								  "Y" => "Address and five-digit Zip match", 
-								  "Z" => "Five-Digit ZIP Matches (No Address)");
-								  
-		$this->CVV2Codes = array(
-									"E" => "N/A", 
-								   	"M" => "Match", 
-								   	"N" => "No Match", 
-								   	"P" => "Not Processed - N/A", 
-								   	"S" => "Service Not Supported - N/A", 
-								   	"U" => "Service Unavailable - N/A", 
-								   	"X" => "No Response - N/A"
-									);
-								   
-		$this->CurrencyCodes = array(
-										'AUD' => 'Austrailian Dollar', 
-										'BRL' => 'Brazilian Real', 
-										'CAD' => 'Canadian Dollar', 
-										'CZK' => 'Czeck Koruna', 
-										'DKK' => 'Danish Krone', 
-										'EUR' => 'Euro', 
-										'HKD' => 'Hong Kong Dollar', 
-										'HUF' => 'Hungarian Forint', 
-										'ILS' => 'Israeli New Sheqel', 
-										'JPY' => 'Japanese Yen', 
-										'MYR' => 'Malaysian Ringgit', 
-										'MXN' => 'Mexican Peso', 
-										'NOK' => 'Norwegian Krone', 
-										'NZD' => 'New Zealand Dollar', 
-										'PHP' => 'Philippine Peso', 
-										'PLN' => 'Polish Zloty', 
-										'GBP' => 'Pound Sterling', 
-										'SGD' => 'Singapore Dollar', 
-										'SEK' => 'Swedish Krona', 
-										'CHF' => 'Swiss Franc', 
-										'TWD' => 'Taiwan New Dollar', 
-										'THB' => 'Thai Baht', 
-										'USD' => 'U.S. Dollar'
-										);
-		
-	
-	}  // End function PayPalPro()
-	
-	/**
-	 * Get the current API version setting.
-	 *
-	 * @access	public
-	 * @return	string	Returns the current value for API version.
-	 */
-	function GetAPIVersion()
-	{
-		return $this->APIVersion;	
-	}
-	
-	/**
-	 * Get the country code of the requested country.
-	 *
-	 * @access	public
-	 * @param	string	$CountryName	Name of the country to return the code for.
-	 * @return	string	Returns the country code for the supplied country name.
-	 */
-	function GetCountryCode($CountryName)
-	{
-		return $this->Countries[$CountryName];
-	}
-	
-	/**
-	 * Get the state code for a requestad state.
-	 *
-	 * @access	public
-	 * @param	string	$StateOrProvinceName	Name of the state or province to return the code for.
-	 * @return	string	Returns the 2-letter code for the supplied state or province name.
-	 */
-	function GetStateCode($StateOrProvinceName)
-	{
-		return $this->States[$StateOrProvinceName];
-	}
-	
-	/**
-	 * Get the country name based on the country code.
-	 *
-	 * @access	public
-	 * @param	string	$CountryCode	Country code that you would like the full name for.
-	 * @return	string	Returns the country name for the supplied country code.
-	 */
-	function GetCountryName($CountryCode)
-	{
-		$Countries = array_flip($this->Countries);
-		return $Countries[$CountryCode];
-	}
-	
-	/**
-	 * Get the state name based on the 2-letter code.
-	 *
-	 * @access	public
-	 * @param	mixed[]	$StateOrProvinceName	State or province name that you would like the full name for.
-	 * @return	string	Returns the full name of the state or province for the supplied code.
-	 */
-	function GetStateName($StateOrProvinceName)
-	{
-		$States = array_flip($this->States);
-		return $States[$StateOrProvinceName];
-	}
-	
-	/**
-	 * Get the AVS (address verification) message.
-	 *
-	 * @access	public
-	 * @param	string	$AVSCode	Address verification result code.
-	 * @return	string	Returns the full message for the supplied AVS code.
-	 */
-	function GetAVSCodeMessage($AVSCode)
-	{					  
-		return $this->AVSCodes[$AVSCode];
-	}
-	
-	/**
-	 * Get the security digits (CVV2 Code) message.
-	 *
-	 * @access	public
-	 * @param	string	$CVV2Code	Credit card security digits.
-	 * @return	string	Returns the full message for the supplied CVV2 code.
-	 */
-	function GetCVV2CodeMessage($CVV2Code)
-	{
-		return $this->CVV2Codes[$CVV2Code];	
-	}
-	
-	/**
-	 * Get the currency code text value.
-	 *
-	 * @access	public
-	 * @param	string	$CurrencyCode	Currency code that you would like the full text for.
-	 * @return	string	Returns the full name for the supplied currency code.
-	 */
-	function GetCurrencyCodeText($CurrencyCode)
-	{
-		return $this->CurrencyCodes[$CurrencyCode];
-	}
-	
-	/**
-	 * Get the currency code based on the text value.
-	 *
-	 * @access	public
-	 * @param	string	$CurrencyCodeText	Full name for a currency.
-	 * @return	string	Returns the full name for the supplied currency code.
-	 */
-	function GetCurrencyCode($CurrencyCodeText)
-	{
-		$CurrencyCodes = array_flip($this->CurrencyCodes);
-		return $CurrencyCodes[$CurrencyCodeText];
-	}
-	
-	/**
-	 * Send the API request to PayPal using CURL.
-	 *
-	 * @access	public
-	 * @param	string	$Request		Raw API request string.
-	 * @param	string	$APIName		The name of the API which you are calling.
-	 * @param	string	$APIOperation	The method of the API which you are calling.
-     * @param   string  $PrintHeaders   The option to print headers or not.
-	 * @return	string	$Response		Returns the raw HTTP response from PayPal.
-	 */
-	function CURLRequest($Request = "", $APIName = "", $APIOperation = "", $PrintHeaders = false)
-	{
-		$curl = curl_init();
-				// curl_setopt($curl, CURLOPT_HEADER,TRUE);
-				curl_setopt($curl, CURLOPT_VERBOSE, $this->Sandbox);
-				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
-				curl_setopt($curl, CURLOPT_TIMEOUT, 30);
-				curl_setopt($curl, CURLOPT_URL, $this->EndPointURL);
-				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
-				curl_setopt($curl, CURLOPT_POSTFIELDS, $Request);
-				
-		if($this->APIMode == 'Certificate')
-		{
-			curl_setopt($curl, CURLOPT_SSLCERT, $this->PathToCertKeyPEM);
-		}
-		
-		$Response = curl_exec($curl);
-		
-		/*
-		 * If a cURL error occurs, output it for review.
-		 */
-		if($this->Sandbox)
-		{
-			if(curl_error($curl))
-			{
-				echo curl_error($curl).'

'; - } - } - - curl_close($curl); - $this->TPV_Parse_Request($Response, $Request, '24' , $this->Sandbox, true); - return $Response; - } - - /** - * Convert an NVP string to an array with URL decoded values. - * - * @access public - * @param string $NVPString Name-value-pair string that you would like to convert to an array. - * @return mixed[] Returns the NVP string as an array structure. - */ - function NVPToArray($NVPString) - { - $proArray = array(); - while(strlen($NVPString)) - { - // name - $keypos= strpos($NVPString,'='); - $keyval = substr($NVPString,0,$keypos); - // value - $valuepos = strpos($NVPString,'&') ? strpos($NVPString,'&'): strlen($NVPString); - $valval = substr($NVPString,$keypos+1,$valuepos-$keypos-1); - // decoding the respose - $proArray[$keyval] = urldecode($valval); - $NVPString = substr($NVPString,$valuepos+1,strlen($NVPString)); - } - - return $proArray; - - } - - /** - * Check whether or not the API call was successful. - * - * @access public - * @param string $ack The value for ACK returned by a PayPal API response. - * @return boolean Returns a boolean (true/false) value for whether or not the ACK supplied is successful. - */ - function APICallSuccessful($ack) - { - if(strtoupper($ack) != 'SUCCESS' && strtoupper($ack) != 'SUCCESSWITHWARNING' && strtoupper($ack) != 'PARTIALSUCCESS') - { - return false; - } - else - { - return true; - } - } - - /** - * Check whether or not warnings were returned. - * - * @access public - * @param string $ack The value for ACK returned by a PayPal API response. - * @return boolean Returns a boolean (true/false) value for whether or not the response includes warnings. - */ - function WarningsReturned($ack) - { - if(strpos(strtoupper($ack),'WARNING') !== false) - { - return true; - } - else - { - false; - } - } - - /** - * Get all errors returned from PayPal. - * - * @access public - * @param mixed[] $DataArray Array structure of PayPal NVP response. - * @return mixed[] $Errors Returns an array structure of all errors / warnings returned in a PayPal HTTP response. - */ - function GetErrors($DataArray) - { - - $Errors = array(); - $n = 0; - while(isset($DataArray['L_ERRORCODE' . $n . ''])) - { - $LErrorCode = isset($DataArray['L_ERRORCODE' . $n . '']) ? $DataArray['L_ERRORCODE' . $n . ''] : ''; - $LShortMessage = isset($DataArray['L_SHORTMESSAGE' . $n . '']) ? $DataArray['L_SHORTMESSAGE' . $n . ''] : ''; - $LLongMessage = isset($DataArray['L_LONGMESSAGE' . $n . '']) ? $DataArray['L_LONGMESSAGE' . $n . ''] : ''; - $LSeverityCode = isset($DataArray['L_SEVERITYCODE' . $n . '']) ? $DataArray['L_SEVERITYCODE' . $n . ''] : ''; - - $CurrentItem = array( - 'L_ERRORCODE' => $LErrorCode, - 'L_SHORTMESSAGE' => $LShortMessage, - 'L_LONGMESSAGE' => $LLongMessage, - 'L_SEVERITYCODE' => $LSeverityCode - ); - - array_push($Errors, $CurrentItem); - $n++; - } - - return $Errors; - - } - - /** - * Display errors on screen using line breaks. - * - * @access public - * @param mixed[] $Errors An array structure of errors returned in a PayPal HTTP response. - * @return output Returns an HTML string of the errors passed in for basic display purposes. - */ - function DisplayErrors($Errors) - { - foreach($Errors as $ErrorVar => $ErrorVal) - { - $CurrentError = $Errors[$ErrorVar]; - foreach($CurrentError as $CurrentErrorVar => $CurrentErrorVal) - { - if($CurrentErrorVar == 'L_ERRORCODE') - { - $CurrentVarName = 'Error Code'; - } - elseif($CurrentErrorVar == 'L_SHORTMESSAGE') - { - $CurrentVarName = 'Short Message'; - } - elseif($CurrentErrorVar == 'L_LONGMESSAGE') - { - $CurrentVarName = 'Long Message'; - } - elseif($CurrentErrorVar == 'L_SEVERITYCODE') - { - $CurrentVarName = 'Severity Code'; - } - - echo $CurrentVarName . ': ' . $CurrentErrorVal . '
'; - } - echo '
'; - } - } - - /** - * Parse order items from an NVP string. - * - * @access public - * @param mixed[] $DataArray An array structure of a PayPal HTTP response. - * @return mixed[] Returns an array structure of the order items included in a PayPal HTTP response. - */ - function GetOrderItems($DataArray) - { - - $OrderItems = array(); - $n = 0; - while(isset($DataArray['L_NAME' . $n . ''])) - { - $LName = isset($DataArray['L_NAME' . $n . '']) ? $DataArray['L_NAME' . $n . ''] : ''; - $LDesc = isset($DataArray['L_DESC' . $n . '']) ? $DataArray['L_DESC' . $n . ''] : ''; - $LNumber = isset($DataArray['L_NUMBER' . $n . '']) ? $DataArray['L_NUMBER' . $n . ''] : ''; - $LQTY = isset($DataArray['L_QTY' . $n . '']) ? $DataArray['L_QTY' . $n . ''] : ''; - $LAmt = isset($DataArray['L_AMT' . $n . '']) ? $DataArray['L_AMT' . $n . ''] : ''; - $LTaxAmt = isset($DataArray['L_TAXAMT' . $n . '']) ? $DataArray['L_TAXAMT' . $n . ''] : ''; - $LOptionsName = isset($DataArray['L_OPTIONSNAME' . $n . '']) ? $DataArray['L_OPTIONSNAME' . $n . ''] : ''; - $LOptionsValue = isset($DataArray['L_OPTIONSVALUE' . $n . '']) ? $DataArray['L_OPTIONSVALUE' . $n . ''] : ''; - $LItemWeightValue = isset($DataArray['L_ITEMWEIGHTVALUE' . $n . '']) ? $DataArray['L_ITEMWEIGHTVALUE' . $n . ''] : ''; - $LItemWeightUnit = isset($DataArray['L_ITEMWEIGHTUNIT' . $n . '']) ? $DataArray['L_ITEMWEIGHTUNIT' . $n . ''] : ''; - $LItemWidthValue = isset($DataArray['L_ITEMWEIGHTVALUE' . $n . '']) ? $DataArray['L_ITEMWEIGHTVALUE' . $n . ''] : ''; - $LItemWidthUnit = isset($DataArray['L_ITEMWIDTHUNIT' . $n . '']) ? $DataArray['L_ITEMWIDTHUNIT' . $n . ''] : ''; - $LItemLengthValue = isset($DataArray['L_ITEMLENGTHVALUE' . $n . '']) ? $DataArray['L_ITEMLENGTHVALUE' . $n . ''] : ''; - $LItemLengthUnit = isset($DataArray['L_ITEMLENGTHUNIT' . $n . '']) ? $DataArray['L_ITEMLENGTHUNIT' . $n . ''] : ''; - $LeBayTransID = isset($DataArray['L_EBAYITEMTXNID' . $n . '']) ? $DataArray['L_EBAYITEMTXNID' . $n . ''] : ''; - $LeBayOrderID = isset($DataArray['L_EBAYITEMORDERID' . $n . '']) ? $DataArray['L_EBAYITEMORDERID' . $n . ''] : ''; - - $CurrentItem = array( - 'L_NAME' => $LName, - 'L_DESC' => $LDesc, - 'L_NUMBER' => $LNumber, - 'L_QTY' => $LQTY, - 'L_AMT' => $LAmt, - 'L_OPTIONSNAME' => $LOptionsName, - 'L_OPTIONSVALUE' => $LOptionsValue, - 'L_ITEMWEIGHTVALUE' => $LItemWeightValue, - 'L_ITEMWEIGHTUNIT' => $LItemWeightUnit, - 'L_ITEMWIDTHVALUE' => $LItemWidthValue, - 'L_ITEMWIDTHUNIT' => $LItemWidthUnit, - 'L_ITEMLENGTHVALUE' => $LItemLengthValue, - 'L_ITEMLENGTHUNIT' => $LItemLengthUnit, - 'L_TAXAMT' => $LTaxAmt, - 'L_EBAYITEMTXNID' => $LeBayTransID, - 'L_EBAYITEMORDERID' => $LeBayOrderID - ); - - array_push($OrderItems, $CurrentItem); - $n++; - } - - return $OrderItems; - - } // End function GetOrderItems - - - /** - * Get all payment(s) details from an NVP string. - * - * @access public - * @param mixed[] $DataArray Array structure from a PayPal HTTP response. - * @return mixed[] Returns an array structure for all of the payments included in a PayPal NVP response. - */ - function GetPayments($DataArray) - { - $Payments = array(); - $n = 0; - while(isset($DataArray['PAYMENTREQUEST_' . $n . '_AMT'])) - { - $Payment = array( - 'SHIPTONAME' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTONAME']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTONAME'] : '', - 'SHIPTOSTREET' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET'] : '', - 'SHIPTOSTREET2' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET2']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET2'] : '', - 'SHIPTOCITY' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCITY']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCITY'] : '', - 'SHIPTOSTATE' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTATE']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTATE'] : '', - 'SHIPTOZIP' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOZIP']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOZIP'] : '', - 'SHIPTOCOUNTRYCODE' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYCODE']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYCODE'] : '', - 'SHIPTOCOUNTRYNAME' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYNAME']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYNAME'] : '', - 'SHIPTOPHONENUM' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOPHONENUM']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOPHONENUM'] : '', - 'ADDRESSSTATUS' => isset($DataArray['PAYMENTREQUEST_' . $n . '_ADDRESSSTATUS']) ? $DataArray['PAYMENTREQUEST_' . $n . '_ADDRESSSTATUS'] : '', - 'AMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_AMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_AMT'] : '', - 'CURRENCYCODE' => isset($DataArray['PAYMENTREQUEST_' . $n . '_CURRENCYCODE']) ? $DataArray['PAYMENTREQUEST_' . $n . '_CURRENCYCODE'] : '', - 'ITEMAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_ITEMAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_ITEMAMT'] : '', - 'SHIPPINGAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPPINGAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPPINGAMT'] : '', - 'INSURANCEOPTIONOFFERED' => isset($DataArray['PAYMENTREQUEST_' . $n . '_INSURANCEOPTIONOFFERED']) ? $DataArray['PAYMENTREQUEST_' . $n . '_INSURANCEOPTIONOFFERED'] : '', - 'HANDLINGAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_HANDLINGAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_HANDLINGAMT'] : '', - 'TAXAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_TAXAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_TAXAMT'] : '', - 'DESC' => isset($DataArray['PAYMENTREQUEST_' . $n . '_DESC']) ? $DataArray['PAYMENTREQUEST_' . $n . '_DESC'] : '', - 'CUSTOM' => isset($DataArray['PAYMENTREQUEST_' . $n . '_CUSTOM']) ? $DataArray['PAYMENTREQUEST_' . $n . '_CUSTOM'] : '', - 'INVNUM' => isset($DataArray['PAYMENTREQUEST_' . $n . '_INVNUM']) ? $DataArray['PAYMENTREQUEST_' . $n . '_INVNUM'] : '', - 'NOTIFYURL' => isset($DataArray['PAYMENTREQUEST_' . $n . '_NOTIFYURL']) ? $DataArray['PAYMENTREQUEST_' . $n . '_NOTIFYURL'] : '', - 'NOTETEXT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_NOTETEXT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_NOTETEXT'] : '', - 'TRANSACTIONID' => isset($DataArray['PAYMENTREQUEST_' . $n . '_TRANSACTIONID']) ? $DataArray['PAYMENTREQUEST_' . $n . '_TRANSACTIONID'] : '', - 'ALLOWEDPAYMENTMETHOD' => isset($DataArray['PAYMENTREQUEST_' . $n . '_ALLOWEDPAYMENTMETHOD']) ? $DataArray['PAYMENTREQUEST_' . $n . '_ALLOWEDPAYMENTMETHOD'] : '', - 'PAYMENTREQUESTID' => isset($DataArray['PAYMENTREQUEST_' . $n . '_PAYMENTREQUESTID']) ? $DataArray['PAYMENTREQUEST_' . $n . '_PAYMENTREQUESTID'] : '' - ); - - $n_items = 0; - $OrderItems = array(); - while(isset($DataArray['L_PAYMENTREQUEST_' . $n . '_AMT' . $n_items])) - { - $Item = array( - 'NAME' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_NAME' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_NAME' . $n_items] : '', - 'DESC' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_DESC' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_DESC' . $n_items] : '', - 'AMT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_AMT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_AMT' . $n_items] : '', - 'NUMBER' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_NUMBER' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_NUMBER' . $n_items] : '', - 'QTY' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_QTY' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_QTY' . $n_items] : '', - 'TAXAMT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_TAXAMT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_TAXAMT' . $n_items] : '', - 'ITEMWEIGHTVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTVALUE' . $n_items] : '', - 'ITEMWEIGHTUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTUNIT' . $n_items] : '', - 'ITEMLENGTHVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHVALUE' . $n_items] : '', - 'ITEMLENGTHUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHUNIT' . $n_items] : '', - 'ITEMWIDTHVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHVALUE' . $n_items] : '', - 'ITEMWIDTHUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHUNIT' . $n_items] : '', - 'ITEMHEIGHTVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTVALUE' . $n_items] : '', - 'ITEMHEIGHTUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTUNIT' . $n_items] : '', - 'EBAYITEMNUMBER' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMNUMBER' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMNUMBER' . $n_items] : '', - 'EBAYAUCTIONTXNID' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYAUCTIONTXNID' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYAUCTIONTXNID' . $n_items] : '', - 'EBAYITEMORDERID' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMORDERID' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMORDERID' . $n_items] : '', - 'EBAYITEMCARTID' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMCARTID' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMCARTID' . $n_items] : '' - ); - - array_push($OrderItems, $Item); - $n_items++; - } - $Payment['ORDERITEMS'] = $OrderItems; - - array_push($Payments, $Payment); - $n++; - } - - return $Payments; - } - - /** - * Parse payment info from Express Checkout API response. - * - * @access public - * @param mixed[] $DataArray Array structure of a PayPal HTTP response. - * @return mixed[] Returns an array structure of the payment details for each payment on a PayPal HTTP response. - */ - function GetExpressCheckoutPaymentInfo($DataArray) - { - $Payments = array(); - $n = 0; - - while(isset($DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONID'])) - { - $PaymentInfo = array( - 'TRANSACTIONID' => isset($DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONID']) ? $DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONID'] : '', - 'TRANSACTIONTYPE' => isset($DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE']) ? $DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE'] : '', - 'PAYMENTTYPE' => isset($DataArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE']) ? $DataArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE'] : '', - 'ORDERTIME' => isset($DataArray['PAYMENTINFO_' . $n . '_ORDERTIME']) ? $DataArray['PAYMENTINFO_' . $n . '_ORDERTIME'] : '', - 'AMT' => isset($DataArray['PAYMENTINFO_' . $n . '_AMT']) ? $DataArray['PAYMENTINFO_' . $n . '_AMT'] : '', - 'CURRENCYCODE' => isset($DataArray['PAYMENTINFO_' . $n . '_CURRENCYCODE']) ? $DataArray['PAYMENTINFO_' . $n . '_CURRENCYCODE'] : '', - 'FEEAMT' => isset($DataArray['PAYMENTINFO_' . $n . '_FEEAMT']) ? $DataArray['PAYMENTINFO_' . $n . '_FEEAMT'] : '', - 'SETTLEAMT' => isset($DataArray['PAYMENTINFO_' . $n . '_SETTLEAMT']) ? $DataArray['PAYMENTINFO_' . $n . '_SETTLEAMT'] : '', - 'TAXAMT' => isset($DataArray['PAYMENTINFO_' . $n . '_TAXAMT']) ? $DataArray['PAYMENTINFO_' . $n . '_TAXAMT'] : '', - 'EXCHANGERATE' => isset($DataArray['PAYMENTINFO_' . $n . '_EXCHANGERATE']) ? $DataArray['PAYMENTINFO_' . $n . '_EXCHANGERATE'] : '', - 'PAYMENTSTATUS' => isset($DataArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS']) ? $DataArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS'] : '', - 'PENDINGREASON' => isset($DataArray['PAYMENTINFO_' . $n . '_PENDINGREASON']) ? $DataArray['PAYMENTINFO_' . $n . '_PENDINGREASON'] : '', - 'REASONCODE' => isset($DataArray['PAYMENTINFO_' . $n . '_REASONCODE']) ? $DataArray['PAYMENTINFO_' . $n . '_REASONCODE'] : '', - 'PROTECTIONELIGIBILITY' => isset($DataArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY']) ? $DataArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY'] : '', - 'EBAYITEMAUCTIONTRANSACTIONID' => isset($DataArray['PAYMENTINFO_' . $n . '_EBAYITEMAUCTIONTRANSACTIONID']) ? $DataArray['PAYMENTINFO_' . $n . '_EBAYITEMAUCTIONTRANSACTIONID'] : '', - 'PAYMENTREQUESTID' => isset($DataArray['PAYMENTINFO_' . $n . '_PAYMENTREQUESTID']) ? $DataArray['PAYMENTINFO_' . $n . '_PAYMENTREQUESTID'] : '' - ); - - array_push($Payments, $PaymentInfo); - $n++; - } - return $Payments; - } - - /** - * Mask the API credential values in the API call for logging purposes. - * - * @access public - * @param string $api_result Raw NVP string. - * @return string Returns the raw NVP string with the API credentials masked. - */ - function MaskAPIResult($api_result) - { - $api_result_array = $this->NVPToArray($api_result); - $api_result=''; - if(isset($api_result_array['SIGNATURE'])) - { - $api_result_array['USER'] = '*****'; - $api_result_array['PWD'] = '*****'; - $api_result_array['SIGNATURE'] = '*****'; - } - if(isset($api_result_array['ACCT'])) - { - $api_result_array['ACCT'] = '*****'.substr($api_result_array['ACCT'],-4); - } - if(isset($api_result_array['CVV2'])) - { - $api_result_array['CVV2'] = '*****'; - } - $api_result=urldecode(http_build_query($api_result_array)); - return $api_result; - } - - /** - * Save log info to a location on the disk. - * - * @param $log_path - * @param $filename - * @param $string_data - * @return bool - */ - function Logger($log_path, $filename, $string_data) - { - - if($this->LogResults) - { - $timestamp = strtotime('now'); - $timestamp = date('mdY_gi_s_A_',$timestamp); - - $string_data_array = $this->NVPToArray($string_data); - - $file = $log_path.$timestamp.$filename.'.txt'; - $fh = fopen($file, 'w'); - fwrite($fh, $string_data.chr(13).chr(13).print_r($string_data_array, true)); - fclose($fh); - } - - return true; - } - - /** - * Captures an authorized payment. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoCapture($DataArray) - { - $DCFieldsNVP = '&METHOD=DoCapture'; - - // DoCapture Fields - $DCFields = isset($DataArray['DCFields']) ? $DataArray['DCFields'] : array(); - - foreach($DCFields as $DCFieldsVar => $DCFieldsVal) - { - $DCFieldsNVP .= $DCFieldsVal != '' ? '&' . strtoupper($DCFieldsVar) . '=' . urlencode($DCFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DCFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - - } - - /** - * Authorize a payment. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoAuthorization($DataArray) - { - $DAFieldsNVP = '&METHOD=DoAuthorization'; - - $DAFields = isset($DataArray['DAFields']) ? $DataArray['DAFields'] : array(); - - foreach($DAFields as $DAFieldsVar => $DAFieldsVal) - { - $DAFieldsNVP .= $DAFieldsVal != '' ? '&' . strtoupper($DAFieldsVar) . '=' . urlencode($DAFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DAFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Reauthorize an existing authorization transaction. - * - * The resulting reauthorization is a new transaction with a new AUTHORIZATIONID. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoReauthorization($DataArray) - { - $DRFieldsNVP = '&METHOD=DoReAuthorization'; - - $DRFields = isset($DataArray['DRFields']) ? $DataArray['DRFields'] : array(); - - foreach($DRFields as $DRFieldsVar => $DRFieldsVal) - { - $DRFieldsNVP .= $DRFieldsVal != '' ? '&' . strtoupper($DRFieldsVar) . '=' . urlencode($DRFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DRFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Change the shipping address of an existing authorization transaction. - * - * In order to use this API operation, the original authorization should - * still be open, not completed, not reversed, not voided, and not on hold - * for any reason. - * - * Advanced permission from PayPal is required to use this API operation. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function UpdateAuthorization($DataArray) - { - $UAFieldsNVP = '&METHOD=UpdateAuthorization'; - - $UAFields = isset($DataArray['UAFields']) ? $DataArray['UAFields'] : array(); - - foreach($UAFields as $UAFieldsVar => $UAFieldsVal) - { - $UAFieldsNVP .= $UAFieldsVal != '' ? '&' . strtoupper($UAFieldsVar) . '=' . urlencode($UAFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $UAFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Void an order or an authorization. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoVoid($DataArray) - { - $DVFieldsNVP = '&METHOD=DoVoid'; - - $DVFields = isset($DataArray['DVFields']) ? $DataArray['DVFields'] : array(); - - foreach($DVFields as $DVFieldsVar => $DVFieldsVal) - { - $DVFieldsNVP .= $DVFieldsVal != '' ? '&' . strtoupper($DVFieldsVar) . '=' . urlencode($DVFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DVFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Make a payment to one or more PayPal account holders. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function MassPay($DataArray) - { - $MPFieldsNVP = '&METHOD=MassPay'; - $MPItemsNVP = ''; - - // MassPay Fields - $MPFields = isset($DataArray['MPFields']) ? $DataArray['MPFields'] : array(); - - foreach($MPFields as $MPFieldsVar => $MPFieldsVal) - { - $MPFieldsNVP .= $MPFieldsVal != '' ? '&' . strtoupper($MPFieldsVar) . '=' . urlencode($MPFieldsVal) : ''; - } - - // MassPay Items Fields - $MPItems = isset($DataArray['MPItems']) ? $DataArray['MPItems'] : array(); - $n = 0; - foreach($MPItems as $MPItemsVar => $MPItemsVal) - { - $CurrentItem = $MPItems[$MPItemsVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $MPItemsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; - } - $n++; - } - - $NVPRequest = $this->NVPCredentials . $MPFieldsNVP . $MPItemsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Issue a refund to the PayPal account holder associated with a transaction. - * - * This API operation can be used to issue a full or partial refund for any transaction - * within a default period of 60 days from when the payment is received. - * - * After the refund period has passed, merchants can no longer use the RefundTransaction - * API operation to issue refunds. Instead, merchants can manually issue a credit to the - * buyer by logging into their PayPal account; for PayPal payments, a credit can be issued - * by clicking Send Money. Alternatively, merchants can use the MassPay API to credit - * PayPal accounts or utilize the DoNonReferencedCredit API operation to issue a credit to - * a card without referencing the original transaction. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function RefundTransaction($DataArray) - { - $RTFieldsNVP = '&METHOD=RefundTransaction'; - - $RTFields = isset($DataArray['RTFields']) ? $DataArray['RTFields'] : array(); - $MerchantDataVars = isset($DataArray['MerchantDataVars']) ? $DataArray['MerchantDataVars'] : array(); - - foreach($RTFields as $RTFieldsVar => $RTFieldsVal) - { - $RTFieldsNVP .= $RTFieldsVal != '' ? '&' . strtoupper($RTFieldsVar) . '=' . urlencode($RTFieldsVal) : ''; - } - - $n = 0; - foreach($MerchantDataVars as $MerchantData) - { - $MerchantDataKey = $MerchantData['key']; - $MerchantDataValue = $MerchantData['value']; - $RTFieldsNVP .= $MerchantData['value'] != '' ? '&MERCHANTDATA' . $n . 'KEY=' . urlencode($MerchantData['key']) . - '&MERCHANTDATA' . $n . 'VALUE=' . urlencode($MerchantData['value']) : ''; - $n++; - } - - $NVPRequest = $this->NVPCredentials . $RTFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Obtain information about a specific transaction. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetTransactionDetails($DataArray) - { - $GTDFieldsNVP = '&METHOD=GetTransactionDetails'; - - $GTDFields = isset($DataArray['GTDFields']) ? $DataArray['GTDFields'] : array(); - - foreach($GTDFields as $GTDFieldsVar => $GTDFieldsVal) - { - $GTDFieldsNVP .= $GTDFieldsVal != '' ? '&' . strtoupper($GTDFieldsVar) . '=' . urlencode($GTDFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $GTDFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - $OrderItems = $this->GetOrderItems($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['ORDERITEMS'] = $OrderItems; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Process a credit card payment. - * - * This is only available with Website Payments Pro 3.0. - * If you're on Payments Pro 2.0 you'll need to use PayFlow instead. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoDirectPayment($DataArray) - { - // Create empty holders for each portion of the NVP string - $DPFieldsNVP = '&METHOD=DoDirectPayment'; - $CCDetailsNVP = ''; - $PayerInfoNVP = ''; - $PayerNameNVP = ''; - $BillingAddressNVP = ''; - $ShippingAddressNVP = ''; - $PaymentDetailsNVP = ''; - $OrderItemsNVP = ''; - $Secure3DNVP = ''; - - // DP Fields - $DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array(); - foreach($DPFields as $DPFieldsVar => $DPFieldsVal) - { - $DPFieldsNVP .= $DPFieldsVal != '' ? '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal) : ''; - } - - // CC Details Fields - $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); - foreach($CCDetails as $CCDetailsVar => $CCDetailsVal) - { - $CCDetailsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; - } - - // PayerInfo Type Fields - $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); - foreach($PayerInfo as $PayerInfoVar => $PayerInfoVal) - { - $PayerInfoNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; - } - - // Payer Name Fields - $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); - foreach($PayerName as $PayerNameVar => $PayerNameVal) - { - $PayerNameNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; - } - - // Address Fields (Billing) - $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); - foreach($BillingAddress as $BillingAddressVar => $BillingAddressVal) - { - $BillingAddressNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; - } - - // Payment Details Type Fields - $PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array(); - foreach($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) - { - $PaymentDetailsNVP .= $PaymentDetailsVal != '' ? '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal) : ''; - } - - // Payment Details Item Type Fields - $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array(); - $n = 0; - foreach($OrderItems as $OrderItemsVar => $OrderItemsVal) - { - $CurrentItem = $OrderItems[$OrderItemsVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $OrderItemsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; - } - $n++; - } - - // Ship To Address Fields - $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); - foreach($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) - { - $ShippingAddressNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; - } - - // 3D Secure Fields - $Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array(); - foreach($Secure3D as $Secure3DVar => $Secure3DVal) - { - $Secure3DNVP .= $Secure3DVal != '' ? '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal) : ''; - } - - // Now that we have each chunk we need to go ahead and append them all together for our entire NVP string - $NVPRequest = $this->NVPCredentials . $DPFieldsNVP . $CCDetailsNVP . $PayerInfoNVP . $PayerNameNVP . $BillingAddressNVP . $PaymentDetailsNVP . $OrderItemsNVP . $ShippingAddressNVP . $Secure3DNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Initiate an Express Checkout transaction. - * - * Used to generate a unique TOKEN for use with the checkout. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function SetExpressCheckout($DataArray) - { - $SECFieldsNVP = '&METHOD=SetExpressCheckout'; - $SurveyChoicesNVP = ''; - $PaymentsNVP = ''; - $ShippingOptionsNVP = ''; - $BillingAgreementsNVP = ''; - - // SetExpressCheckout Request Fields - $SECFields = isset($DataArray['SECFields']) ? $DataArray['SECFields'] : array(); - foreach($SECFields as $SECFieldsVar => $SECFieldsVal) - { - if(strtoupper($SECFieldsVar) != 'SKIPDETAILS') - { - $SECFieldsNVP .= $SECFieldsVal != '' ? '&' . strtoupper($SECFieldsVar) . '=' . urlencode($SECFieldsVal) : ''; - } - else - { - $SkipDetails = $SECFieldsVal ? true : false; - } - } - - // Check to see if the REDIRECTURL should include user-action - if(isset($SkipDetails) && $SkipDetails) - { - $SkipDetailsOption = 'useraction=commit'; - } - else - { - $SkipDetailsOption = 'useraction=continue'; - } - - // Survey Choices - $SurveyChoices = isset($DataArray['SurveyChoices']) ? $DataArray['SurveyChoices'] : array(); - if(isset($SECFields['surveyquestion']) && $SECFields['surveyquestion'] != '') - { - $n = 0; - foreach($SurveyChoices as $SurveyChoice) - { - $SurveyChoicesNVP .= $SurveyChoice != '' ? '&' . 'L_SURVEYCHOICE' . $n . '=' . urlencode($SurveyChoice) : ''; - $n++; - } - } - - // Payment Details Type Fields - $Payments = isset($DataArray['Payments']) ? $DataArray['Payments'] : array(); - $n = 0; - foreach($Payments as $PaymentsVar => $PaymentsVal) - { - $CurrentPayment = $Payments[$PaymentsVar]; - foreach($CurrentPayment as $CurrentPaymentVar => $CurrentPaymentVal) - { - if(strtoupper($CurrentPaymentVar) != 'ORDER_ITEMS') - { - $PaymentsNVP .= $CurrentPaymentVal != '' ? '&PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentPaymentVar) . '=' . urlencode($CurrentPaymentVal) : ''; - } - else - { - $PaymentOrderItems = $CurrentPayment['order_items']; - $n_item = 0; - foreach($PaymentOrderItems as $OrderItemsVar => $OrderItemsVal) - { - $CurrentItem = $PaymentOrderItems[$OrderItemsVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $PaymentsNVP .= $CurrentItemVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentItemVar) . $n_item . '=' . urlencode($CurrentItemVal) : ''; - } - $n_item++; - } - } - } - $n++; - } - - // Billing Agreements - $BillingAgreements = isset($DataArray['BillingAgreements']) ? $DataArray['BillingAgreements'] : array(); - $n = 0; - foreach($BillingAgreements as $BillingAgreementVar => $BillingAgreementVal) - { - $CurrentItem = $BillingAgreements[$BillingAgreementVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $BillingAgreementsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; - } - $n++; - } - - // Shipping Options Fields - $ShippingOptions = isset($DataArray['ShippingOptions']) ? $DataArray['ShippingOptions'] : array(); - $n = 0; - foreach($ShippingOptions as $ShippingOptionsVar => $ShippingOptionsVal) - { - $CurrentOption = $ShippingOptions[$ShippingOptionsVar]; - foreach($CurrentOption as $CurrentOptionVar => $CurrentOptionVal) - { - $ShippingOptionsNVP .= $CurrentOptionVal != '' ? '&' . strtoupper($CurrentOptionVar) . $n . '=' . urlencode($CurrentOptionVal) : ''; - } - $n++; - } - - $NVPRequest = $this->NVPCredentials . $SECFieldsNVP . $SurveyChoicesNVP . $ShippingOptionsNVP . $BillingAgreementsNVP . $PaymentsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - if(isset($NVPResponseArray['TOKEN']) && $NVPResponseArray['TOKEN'] != '') - { - if($this->Sandbox) - { - $NVPResponseArray['REDIRECTURLDIGITALGOODS'] = 'https://www.sandbox.paypal.com/incontext?'.$SkipDetailsOption.'&token='.$NVPResponseArray['TOKEN']; - $NVPResponseArray['REDIRECTURL'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&' . $SkipDetailsOption . '&token=' . $NVPResponseArray['TOKEN']; - } - else - { - $NVPResponseArray['REDIRECTURLDIGITALGOODS'] = 'https://www.paypal.com/incontext?'.$SkipDetailsOption.'&token='.$NVPResponseArray['TOKEN']; - $NVPResponseArray['REDIRECTURL'] = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&' . $SkipDetailsOption . '&token=' . $NVPResponseArray['TOKEN']; - } - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } // End function SetExpressCheckout() - - /** - * Generate an NVP response to return to PayPal's Instant Update (callback) API. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function CallbackResponse($DataArray) - { - $CBFieldsNVP = 'METHOD=CallbackResponse'; - $ShippingOptionsNVP = ''; - - // Basic callback response fields. - $CBFields = isset($DataArray['CBFields']) ? $DataArray['CBFields'] : array(); - foreach($CBFields as $CBFieldsVar => $CBFieldsVal) - { - $CBFieldsNVP .= $CBFieldsVal != '' ? '&' . strtoupper($CBFieldsVar) . '=' . urlencode($CBFieldsVal) : ''; - } - - // Shipping Options Fields - $ShippingOptions = isset($DataArray['ShippingOptions']) ? $DataArray['ShippingOptions'] : array(); - $n = 0; - foreach($ShippingOptions as $ShippingOptionsVar => $ShippingOptionsVal) - { - $CurrentOption = $ShippingOptions[$ShippingOptionsVar]; - foreach($CurrentOption as $CurrentOptionVar => $CurrentOptionVal) - { - $ShippingOptionsNVP .= $CurrentOptionVal != '' ? '&' . strtoupper($CurrentOptionVar) . $n . '=' . urlencode($CurrentOptionVal) : ''; - } - $n++; - } - - $NVPResponse = $CBFieldsNVP . $ShippingOptionsNVP; - - $this->Logger($this->LogPath, __FUNCTION__, $NVPResponse); - - return $NVPResponse; - - } - - /** - * Obtain details about an Express Checkout transaction. - * - * This is used after PayPal redirects the buyer back to your - * ReturnURL supplied in the SetExpressCheckout request. Data - * returned includes the buyer's name, shipping address, phone number, - * and general transaction details. - * - * @access public - * @param string $Token The token returned from a previous SetExpressCheckout request. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetExpressCheckoutDetails($Token) - { - $GECDFieldsNVP = '&METHOD=GetExpressCheckoutDetails&TOKEN=' . $Token; - - $NVPRequest = $this->NVPCredentials . $GECDFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - $OrderItems = $this->GetOrderItems($NVPResponseArray); - $Payments = $this->GetPayments($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['ORDERITEMS'] = $OrderItems; - $NVPResponseArray['PAYMENTS'] = $Payments; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - - } // End function GetExpressCheckoutDetails() - - /** - * Complete an Express Checkout transaction. - * - * If you set up a billing agreement in your SetExpressCheckout API call, - * the billing agreement is created when you call the DoExpressCheckoutPayment - * API operation. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoExpressCheckoutPayment($DataArray) - { - $DECPFieldsNVP = '&METHOD=DoExpressCheckoutPayment'; - $PaymentsNVP = ''; - $UserSelectedOptionsNVP = ''; - - // DoExpressCheckoutPayment Fields - $DECPFields = isset($DataArray['DECPFields']) ? $DataArray['DECPFields'] : array(); - foreach($DECPFields as $DECPFieldsVar => $DECPFieldsVal) - { - $DECPFieldsNVP .= $DECPFieldsVal != '' ? '&' . strtoupper($DECPFieldsVar) . '=' . urlencode($DECPFieldsVal) : ''; - } - - // Payment Details Type Fields - $Payments = isset($DataArray['Payments']) ? $DataArray['Payments'] : array(); - $n = 0; - foreach($Payments as $PaymentsVar => $PaymentsVal) - { - $CurrentPayment = $Payments[$PaymentsVar]; - foreach($CurrentPayment as $CurrentPaymentVar => $CurrentPaymentVal) - { - if(strtoupper($CurrentPaymentVar) == 'ORDER_ITEMS') - { - $PaymentOrderItems = $CurrentPayment['order_items']; - $n_item = 0; - foreach($PaymentOrderItems as $OrderItemsVar => $OrderItemsVal) - { - $CurrentItem = $PaymentOrderItems[$OrderItemsVar]; - foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $PaymentsNVP .= $CurrentItemVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentItemVar) . $n_item . '=' . urlencode($CurrentItemVal) : ''; - } - $n_item++; - } - } - elseif(strtoupper($CurrentPaymentVar) == 'REDEEMED_OFFERS') - { - $RedeemedOffers = $CurrentPayment['redeemed_offers']; - $n_item = 0; - foreach($RedeemedOffers as $RedeemedOfferVar => $RedeemedOfferVal) - { - $CurrentRedeemedOffer = $RedeemedOffers[$RedeemedOfferVar]; - foreach ($CurrentRedeemedOffer as $CurrentRedeemedOfferVar => $CurrentRedeemedOfferVal) - { - $PaymentsNVP .= $CurrentRedeemedOfferVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentRedeemedOfferVar) . $n_item . '=' . urlencode($CurrentRedeemedOfferVal) : ''; - } - $n_item++; - } - } - elseif(strtoupper($CurrentPaymentVar) == 'MERCHANT_DATA_VARS') - { - $MerchantDataVars = $CurrentPayment['merchant_data_vars']; - $n_item = 0; - foreach($MerchantDataVars as $MerchantDataVarsVar => $MerchantDataVarsVal) - { - $CurrentMerchantDataVar = $MerchantDataVars[$MerchantDataVarsVar]; - foreach ($CurrentMerchantDataVar as $CurrentMerchantDataVarVar => $CurrentMerchantDataVarVal) - { - $PaymentsNVP .= $CurrentMerchantDataVarVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentMerchantDataVarVar) . $n_item . '=' . urlencode($CurrentMerchantDataVarVal) : ''; - } - $n_item++; - } - } - else - { - $PaymentsNVP .= $CurrentPaymentVal != '' ? '&PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentPaymentVar) . '=' . urlencode($CurrentPaymentVal) : ''; - } - } - $n++; - } - - // User Selected Options - $UserSelectedOptions = isset($DataArray['UserSelectedOptions']) ? $DataArray['UserSelectedOptions'] : array(); - foreach($UserSelectedOptions as $UserSelectedOptionVar => $UserSelectedOptionVal) - { - $UserSelectedOptionsNVP .= $UserSelectedOptionVal != '' ? '&' . strtoupper($UserSelectedOptionVar) . '=' . urlencode($UserSelectedOptionVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DECPFieldsNVP . $PaymentsNVP . $UserSelectedOptionsNVP; - $this->MaskAPIResult($NVPRequest); - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - // Loop through all possible payments and parse out data accordingly. - // This is to handle parallel payments. - $n = 0; - $Payments = array(); - while(isset($NVPResponseArray['PAYMENTINFO_' . $n . '_AMT'])) - { - $Payment = array( - 'TRANSACTIONID' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONID']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONID'] : '', - 'TRANSACTIONTYPE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE'] : '', - 'PAYMENTTYPE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE'] : '', - 'ORDERTIME' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_ORDERTIME']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_ORDERTIME'] : '', - 'AMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_AMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_AMT'] : '', - 'FEEAMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_FEEAMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_FEEAMT'] : '', - 'SETTLEAMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_SETTLEAMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_SETTLEAMT'] : '', - 'TAXAMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_TAXAMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_TAXAMT'] : '', - 'EXCHANGERATE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_EXCHANGERATE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_EXCHANGERATE'] : '', - 'CURRENCYCODE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_CURRENCYCODE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_CURRENCYCODE'] : '', - 'PAYMENTSTATUS' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS'] : '', - 'PENDINGREASON' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PENDINGREASON']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PENDINGREASON'] : '', - 'REASONCODE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_REASONCODE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_REASONCODE'] : '', - 'PROTECTIONELIGIBILITY' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY'] : '', - 'ERRORCODE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_ERRORCODE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_ERRORCODE'] : '' - ); - - // Pull out FMF info for current payment. - $FMFilters = array(); - $n_filters = 0; - while(isset($NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERID' . $n_filters])) - { - $FMFilter = array( - 'ID' => isset($NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERID' . $n_filters]) ? $NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERID' . $n_filters] : '', - 'NAME' => isset($NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERNAME' . $n_filters]) ? $NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERNAME' . $n_filters] : '' - ); - $n_filters++; - } - $Payment['FMFILTERS'] = $FMFilters; - - // Pull error info for current payment. - $PaymentErrors = array(); - while(isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_ERRORCODE'])) - { - $Error = array( - 'ERRORCODE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_ERRORCODE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_ERRORCODE'] : '', - 'SHORTMESSAGE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_SHORTMESSAGE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_SHORTMESSAGE'] : '', - 'LONGMESSAGE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_LONGMESSAGE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_LONGMESSAGE'] : '', - 'SEVERITYCODE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_SEVERITYCODE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_SEVERITYCODE'] : '', - 'ACK' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_ACK']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_ACK'] : '' - ); - array_push($PaymentErrors, $Error); - } - $Payment['ERRORS'] = $PaymentErrors; - - array_push($Payments, $Payment); - $n++; - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['PAYMENTS'] = $Payments; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Search PayPal transaction history for transactions that meet the specified criteria. - * - * The maximum number of transactions that can be returned from a TransactionSearch API call is 100. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function TransactionSearch($DataArray) - { - $TSFieldsNVP = '&METHOD=TransactionSearch'; - $PayerNameNVP = ''; - - // Transaction Search Fields - $TSFields = isset($DataArray['TSFields']) ? $DataArray['TSFields'] : array(); - foreach($TSFields as $TSFieldsVar => $TSFieldsVal) - { - $TSFieldsNVP .= $TSFieldsVal != '' ? '&' . strtoupper($TSFieldsVar) . '=' . urlencode($TSFieldsVal) : ''; - } - - // Payer Name Fields - $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); - foreach($PayerName as $PayerNameVar => $PayerNameVal) - { - $PayerNameNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $TSFieldsNVP . $PayerNameNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $SearchResults = array(); - $n = 0; - while(isset($NVPResponseArray['L_TIMESTAMP' . $n . ''])) - { - $LTimestamp = isset($NVPResponseArray['L_TIMESTAMP' . $n . '']) ? $NVPResponseArray['L_TIMESTAMP' . $n . ''] : ''; - $LTimeZone = isset($NVPResponseArray['L_TIMEZONE' . $n . '']) ? $NVPResponseArray['L_TIMEZONE' . $n . ''] : ''; - $LType = isset($NVPResponseArray['L_TYPE' . $n . '']) ? $NVPResponseArray['L_TYPE' . $n . ''] : ''; - $LEmail = isset($NVPResponseArray['L_EMAIL' . $n . '']) ? $NVPResponseArray['L_EMAIL' . $n . ''] : ''; - $LName = isset($NVPResponseArray['L_NAME' . $n . '']) ? $NVPResponseArray['L_NAME' . $n . ''] : ''; - $LTransID = isset($NVPResponseArray['L_TRANSACTIONID' . $n . '']) ? $NVPResponseArray['L_TRANSACTIONID' . $n . ''] : ''; - $LStatus = isset($NVPResponseArray['L_STATUS' . $n . '']) ? $NVPResponseArray['L_STATUS' . $n . ''] : ''; - $LAmt = isset($NVPResponseArray['L_AMT' . $n . '']) ? $NVPResponseArray['L_AMT' . $n . ''] : ''; - $LFeeAmt = isset($NVPResponseArray['L_FEEAMT' . $n . '']) ? $NVPResponseArray['L_FEEAMT' . $n . ''] : ''; - $LNetAmt = isset($NVPResponseArray['L_NETAMT' . $n . '']) ? $NVPResponseArray['L_NETAMT' . $n . ''] : ''; - - $CurrentItem = array( - 'L_TIMESTAMP' => $LTimestamp, - 'L_TIMEZONE' => $LTimeZone, - 'L_TYPE' => $LType, - 'L_EMAIL' => $LEmail, - 'L_NAME' => $LName, - 'L_TRANSACTIONID' => $LTransID, - 'L_STATUS' => $LStatus, - 'L_AMT' => $LAmt, - 'L_FEEAMT' => $LFeeAmt, - 'L_NETAMT' => $LNetAmt - ); - - array_push($SearchResults, $CurrentItem); - $n++; - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['SEARCHRESULTS'] = $SearchResults; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - - } - - /** - * Issue a credit to a card not referenced by the original transaction. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoNonReferencedCredit($DataArray) - { - $DNRCFieldsNVP = '&METHOD=DoNonReferencedCredit'; - $CCDetailsNVP = ''; - $PayerNameNVP = ''; - $PayerInfoNVP = ''; - $BillingAddressNVP = ''; - - // DoNonReferencedCredit Fields - $DNRCFields = isset($DataArray['DNRCFields']) ? $DataArray['DNRCFields'] : array(); - foreach($DNRCFields as $DNRCFieldsVar => $DNRCFieldsVal) - { - $DNRCFieldsNVP .= $DNRCFieldsVal != '' ? '&' . strtoupper($DNRCFieldsVar) . '=' . urlencode($DNRCFieldsVal) : ''; - } - - // CC Details Fields - $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); - foreach($CCDetails as $CCDetailsVar => $CCDetailsVal) - { - $CCDetailsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; - } - - // Payer Name Fields - $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); - foreach($PayerName as $PayerNameVar => $PayerNameVal) - { - $PayerNameNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; - } - - // Payer Info Fields - $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); - foreach($PayerInfo as $PayerInfoVar => $PayerInfoVal) - { - $PayerInfoNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; - } - - // Address Fields (Billing) - $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); - foreach($BillingAddress as $BillingAddressVar => $BillingAddressVal) - { - $BillingAddressNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DNRCFieldsNVP . $CCDetailsNVP . $PayerNameNVP . $PayerInfoNVP . $BillingAddressNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Process a payment from a buyer's account, which is identified by a previous transaction. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoReferenceTransaction($DataArray) - { - $DRTFieldsNVP = '&METHOD=DoReferenceTransaction'; - $CCDetailsNVP = ''; - $PayerInfoNVP = ''; - $BillingAddressNVP = ''; - $ShippingAddressNVP = ''; - $PaymentDetailsNVP = ''; - $OrderItemsNVP = ''; - - // DoReferenceTransaction Fields - $DRTFields = isset($DataArray['DRTFields']) ? $DataArray['DRTFields'] : array(); - foreach($DRTFields as $DRTFieldsVar => $DRTFieldsVal) - { - $DRTFieldsNVP .= $DRTFieldsVal != '' ? '&' . strtoupper($DRTFieldsVar) . '=' . urlencode($DRTFieldsVal) : ''; - } - - // Ship To Address Fields - $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); - foreach($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) - { - $ShippingAddressNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; - } - - // Payment Details Item Type Fields - $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array(); - $n = 0; - foreach($OrderItems as $OrderItemsVar => $OrderItemsVal) - { - $CurrentItem = $OrderItems[$OrderItemsVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $OrderItemsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; - } - $n++; - } - - // CC Details Fields - $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); - foreach($CCDetails as $CCDetailsVar => $CCDetailsVal) - { - $CCDetailsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; - } - - // PayerInfo Type Fields - $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); - foreach($PayerInfo as $PayerInfoVar => $PayerInfoVal) - { - $PayerInfoNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; - } - - // Address Fields (Billing) - $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); - foreach($BillingAddress as $BillingAddressVar => $BillingAddressVal) - { - $BillingAddressNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; - } - - // Payment Details Fields - $PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array(); - foreach($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) - { - $PaymentDetailsNVP .= $PaymentDetailsVal != '' ? '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DRTFieldsNVP . $ShippingAddressNVP . $OrderItemsNVP . $CCDetailsNVP . $PayerInfoNVP . $BillingAddressNVP . $PaymentDetailsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Obtain the available balance for a PayPal account. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed balance results, errors and the raw request/response. - */ - function GetBalance($DataArray) - { - $GBFieldsNVP = '&METHOD=GetBalance'; - - // GetBalance Fields - $GBFields = isset($DataArray['GBFields']) ? $DataArray['GBFields'] : array(); - foreach($GBFields as $GBFieldsVar => $GBFieldsVal) - { - $GBFieldsNVP .= $GBFieldsVal != '' ? '&' . strtoupper($GBFieldsVar) . '=' . urlencode($GBFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $GBFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $BalanceResults = array(); - $n = 0; - while(isset($NVPResponseArray['L_AMT' . $n . ''])) - { - $LAmt = isset($NVPResponseArray['L_AMT' . $n . '']) ? $NVPResponseArray['L_AMT' . $n . ''] : ''; - $LCurrencyCode = isset($NVPResponseArray['L_CURRENCYCODE' . $n . '']) ? $NVPResponseArray['L_CURRENCYCODE' . $n . ''] : ''; - - $CurrentItem = array( - 'L_AMT' => $LAmt, - 'L_CURRENCYCODE' => $LCurrencyCode - ); - - array_push($BalanceResults, $CurrentItem); - $n++; - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['BALANCERESULTS'] = $BalanceResults; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Obtain your Pal ID, which is the PayPal–assigned merchant account number, and other informaton about your account. - * - * You need the encrypted account number when working with dynamic versions of PayPal buttons and logos. - * - * @access public - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetPalDetails() - { - $GPFieldsNVP = '&METHOD=GetPalDetails'; - - $NVPRequest = $this->NVPCredentials . $GPFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Confirm whether a postal address and postal code match those of the specified PayPal account holder. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function AddressVerify($DataArray) - { - $AVFieldsNVP = '&METHOD=AddressVerify'; - - $AVFields = isset($DataArray['AVFields']) ? $DataArray['AVFields'] : array(); - foreach($AVFields as $AVFieldsVar => $AVFieldsVal) - { - $AVFieldsNVP .= $AVFieldsVal != '' ? '&' . strtoupper($AVFieldsVar) . '=' . urlencode($AVFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $AVFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Accept or deny a pending transaction held by Fraud Management Filters. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function ManagePendingTransactionStatus($DataArray) - { - $MPTSFieldsNVP = '&METHOD=ManagePendingTransactionStatus'; - - $MPTSFields = isset($DataArray['MPTSFields']) ? $DataArray['MPTSFields'] : array(); - foreach($MPTSFields as $MPTSFieldsVar => $MPTSFieldsVal) - { - $MPTSFieldsNVP .= $MPTSFieldsVal != '' ? '&' . strtoupper($MPTSFieldsVar) . '=' . urlencode($MPTSFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $MPTSFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Create a recurring payments profile. - * - * You must invoke the CreateRecurringPaymentsProfile API operation for each - * profile you want to create. The API operation creates a profile and an - * associated billing agreement. - * - * There is a one-to-one correspondence between billing agreements and - * recurring payments profiles. To associate a recurring payments profile - * with its billing agreement, you must ensure that the description in the - * recurring payments profile matches the description of a billing agreement. - * For version 54.0 and later, use SetExpressCheckout to initiate creation of - * a billing agreement. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function CreateRecurringPaymentsProfile($DataArray) - { - $CRPPFieldsNVP = '&METHOD=CreateRecurringPaymentsProfile'; - $OrderItemsNVP = ''; - - $CRPPFields = isset($DataArray['CRPPFields']) ? $DataArray['CRPPFields'] : array(); - foreach($CRPPFields as $CRPPFieldsVar => $CRPPFieldsVal) - { - $CRPPFieldsNVP .= $CRPPFieldsVal != '' ? '&' . strtoupper($CRPPFieldsVar) . '=' . urlencode($CRPPFieldsVal) : ''; - } - - $ProfileDetails = isset($DataArray['ProfileDetails']) ? $DataArray['ProfileDetails'] : array(); - foreach($ProfileDetails as $ProfileDetailsVar => $ProfileDetailsVal) - { - $CRPPFieldsNVP .= $ProfileDetailsVal != '' ? '&' . strtoupper($ProfileDetailsVar) . '=' . urlencode($ProfileDetailsVal) : ''; - } - - $ScheduleDetails = isset($DataArray['ScheduleDetails']) ? $DataArray['ScheduleDetails'] : array(); - foreach($ScheduleDetails as $ScheduleDetailsVar => $ScheduleDetailsVal) - { - $CRPPFieldsNVP .= $ScheduleDetailsVal != '' ? '&' . strtoupper($ScheduleDetailsVar) . '=' . urlencode($ScheduleDetailsVal) : ''; - } - - $BillingPeriod = isset($DataArray['BillingPeriod']) ? $DataArray['BillingPeriod'] : array(); - foreach($BillingPeriod as $BillingPeriodVar => $BillingPeriodVal) - { - $CRPPFieldsNVP .= $BillingPeriodVal != '' ? '&' . strtoupper($BillingPeriodVar) . '=' . urlencode($BillingPeriodVal) : ''; - } - - $ActivationDetails = isset($DataArray['ActivationDetails']) ? $DataArray['ActivationDetails'] : array(); - foreach($ActivationDetails as $ActivationDetailsVar => $ActivationDetailsVal) - { - $CRPPFieldsNVP .= $ActivationDetailsVal != '' ? '&' . strtoupper($ActivationDetailsVar) . '=' . urlencode($ActivationDetailsVal) : ''; - } - - $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); - foreach($CCDetails as $CCDetailsVar => $CCDetailsVal) - { - $CRPPFieldsNVP .= $CCDetails != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; - } - - $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); - foreach($PayerInfo as $PayerInfoVar => $PayerInfoVal) - { - $CRPPFieldsNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; - } - - $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); - foreach($PayerName as $PayerNameVar => $PayerNameVal) - { - $CRPPFieldsNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; - } - - $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); - foreach($BillingAddress as $BillingAddressVar => $BillingAddressVal) - { - $CRPPFieldsNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; - } - - $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); - foreach($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) - { - $CRPPFieldsNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; - } - - // Payment Details Item Type Fields - $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array(); - $n = 0; - $m = 0; - foreach($OrderItems as $OrderItemsVar => $OrderItemsVal) - { - $CurrentItem = $OrderItems[$OrderItemsVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $OrderItemsNVP .= $CurrentItemVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentItemVar) . $m . '=' . urlencode($CurrentItemVal) : ''; - } - $m++; - } - - $NVPRequest = $this->NVPCredentials . $CRPPFieldsNVP . $OrderItemsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Obtain information about a recurring payments profile. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetRecurringPaymentsProfileDetails($DataArray) - { - $GRPPDFieldsNVP = '&METHOD=GetRecurringPaymentsProfileDetails'; - - $GRPPDFields = isset($DataArray['GRPPDFields']) ? $DataArray['GRPPDFields'] : array(); - foreach($GRPPDFields as $GRPPDFieldsVar => $GRPPDFieldsVal) - { - $GRPPDFieldsNVP .= $GRPPDFieldsVal != '' ? '&' . strtoupper($GRPPDFieldsVar) . '=' . urlencode($GRPPDFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $GRPPDFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Cancel, suspend, or reactivate a recurring payments profile. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function ManageRecurringPaymentsProfileStatus($DataArray) - { - $MRPPSFieldsNVP = '&METHOD=ManageRecurringPaymentsProfileStatus'; - - $MRPPSFields = isset($DataArray['MRPPSFields']) ? $DataArray['MRPPSFields'] : array(); - foreach($MRPPSFields as $MRPPSFieldsVar => $MRPPSFieldsVal) - { - $MRPPSFieldsNVP .= $MRPPSFieldsVal != '' ? '&' . strtoupper($MRPPSFieldsVar) . '=' . urlencode($MRPPSFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $MRPPSFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Bill the buyer for the outstanding balance associated with a recurring payments profile. - * - * To bill the outstanding amount: - * - The profile status must be active or suspended. - * - The profile must have a non-zero outstanding balance. - * - The amount of the payment cannot exceed the outstanding amount for the profile. - * - * The BillOutstandingAmount call cannot be within 24 hours of a regularly scheduled payment for this profile. - * - * If another outstanding balance payment is already queued, an API error is returned. - * - * You will be informed by IPN about the success or failure of the outstanding payment. - * For profiles created using Express Checkout, the buyer will receive an email notification of the payment. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function BillOutstandingAmount($DataArray) - { - $BOAFieldsNVP = '&METHOD=BillOutstandingAmount'; - - $BOAFields = isset($DataArray['BOAFields']) ? $DataArray['BOAFields'] : array(); - foreach($BOAFields as $BOAFieldsVar => $BOAFieldsVal) - { - $BOAFieldsNVP .= $BOAFieldsVal != '' ? '&' . strtoupper($BOAFieldsVar) . '=' . urlencode($BOAFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $BOAFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Update a recurring payments profile. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function UpdateRecurringPaymentsProfile($DataArray) - { - $URPPFieldsNVP = '&METHOD=UpdateRecurringPaymentsProfile'; - - $URPPFields = isset($DataArray['URPPFields']) ? $DataArray['URPPFields'] : array(); - foreach($URPPFields as $URPPFieldsVar => $URPPFieldsVal) - { - $URPPFieldsNVP .= $URPPFieldsVal != '' ? '&' . strtoupper($URPPFieldsVar) . '=' . urlencode($URPPFieldsVal) : ''; - } - - $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); - foreach($BillingAddress as $BillingAddressVar => $BillingAddressVal) - { - $URPPFieldsNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; - } - - $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); - foreach($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) - { - $URPPFieldsNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; - } - - $BillingPeriod = isset($DataArray['BillingPeriod']) ? $DataArray['BillingPeriod'] : array(); - foreach($BillingPeriod as $BillingPeriodVar => $BillingPeriodVal) - { - $URPPFieldsNVP .= $BillingPeriodVal != '' ? '&' . strtoupper($BillingPeriodVar) . '=' . urlencode($BillingPeriodVal) : ''; - } - - $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); - foreach($CCDetails as $CCDetailsVar => $CCDetailsVal) - { - $URPPFieldsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; - } - - $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); - foreach($PayerInfo as $PayerInfoVar => $PayerInfoVal) - { - $URPPFieldsNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $URPPFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Obtain information about a recurring payments profile. - * - * @access public - * @param string $ProfileID The ID of a recurring payments profile. - * @return mixed[] Returns an array structure consisting of the full result as well as the parsed profile status. - */ - function GetRecurringPaymentsProfileStatus($ProfileID) - { - $GRPPDFields = array('profileid' => $ProfileID); - $PayPalRequestData = array('GRPPDFields' => $GRPPDFields); - - $PayPalResult = $this->GetRecurringPaymentsProfileDetails($PayPalRequestData); - $PayPalErrors = $PayPalResult['ERRORS']; - $ProfileStatus = isset($PayPalResult['STATUS']) ? $PayPalResult['STATUS'] : 'Unknown'; - - $ResponseArray = array( - 'PayPalResult' => $PayPalResult, - 'ProfileStatus' => $ProfileStatus - ); - - return $ResponseArray; - } - - /** - * Create a billing agreement with a PayPal account holder. - * - * CreateBillingAgreement is only valid for reference transactions. - * - * @access public - * @param string $Token A token returned from a previous SetExpressCheckout request. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - * - */ - function CreateBillingAgreement($Token) - { - $CBAFieldsNVP = '&METHOD=CreateBillingAgreement&TOKEN='.urlencode($Token); - - $NVPRequest = $this->NVPCredentials . $CBAFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Initiate the creation of a billing agreement. - * - * When using Express Checkout with version 54.0 or later of the API, - * do not use SetCustomerBillingAgreement and GetBillingAgreementCustomerDetails. - * Instead, use SetExpressCheckout and set the amount value to zero. Call - * GetExpressCheckoutDetails to obtain information about the buyer's checkout - * status. Then use the CreateBillingAgreement API to create the abilling agreement. - * - * @access public - * @deprecated No longer used in PayPal API version 54.0 or higher. - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function SetCustomerBillingAgreement($DataArray) - { - $SCBAFieldsNVP = '&METHOD=SetCustomerBillingAgreement'; - $BillingAgreementsNVP = ''; - - $SCBAFields = isset($DataArray['SCBAFields']) ? $DataArray['SCBAFields'] : array(); - foreach($SCBAFields as $SCBAFieldsVar => $SCBAFieldsVal) - { - $SCBAFieldsNVP .= $SCBAFieldsVal != '' ? '&' . strtoupper($SCBAFieldsVar) . '=' . urlencode($SCBAFieldsVal) : ''; - } - - $BillingAgreements = isset($DataArray['BillingAgreements']) ? $DataArray['BillingAgreements'] : array(); - $n = 0; - foreach($BillingAgreements as $BillingAgreementVar => $BillingAgreementVal) - { - $CurrentItem = $BillingAgreements[$BillingAgreementVar]; - foreach($CurrentItem as $CurrentItemVar => $CurrentItemVal) - { - $BillingAgreementsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; - } - $n++; - } - - $NVPRequest = $this->NVPCredentials . $SCBAFieldsNVP . $BillingAgreementsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Obtain information about a billing agreement's PayPal account holder - * - * When using Express Checkout with version 54.0 or later of the API, - * do not use SetCustomerBillingAgreement and GetBillingAgreementCustomerDetails. - * Instead, use SetExpressCheckout and set the amount value to zero. Call - * GetExpressCheckoutDetails to obtain information about the buyer's checkout - * status. Then use the CreateBillingAgreement API to create the abilling agreement. - - * @access public - * @deprecated No longer used in PayPal API version 54.0 or higher. - * @param string $Token Token returned by a previous SetCustomerBillingAgreement request. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetBillingAgreementCustomerDetails($Token) - { - $GBACDFieldsNVP = '&METHOD=GetBillingAgreementCustomerDetails&TOKEN=' . $Token; - - $NVPRequest = $this->NVPCredentials . $GBACDFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Update or delete a billing agreement. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function BillAgreementUpdate($DataArray) - { - $BAUFieldsNVP = '&METHOD=BillAgreementUpdate'; - - $BAUFields = isset($DataArray['BAUFields']) ? $DataArray['BAUFields'] : array(); - foreach($BAUFields as $BAUFieldsVar => $BAUFieldsVal) - { - $BAUFieldsNVP .= $BAUFieldsVal != '' ? '&' . strtoupper($BAUFieldsVar) . '=' . urlencode($BAUFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $BAUFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - - } - - /** - * Setup the mobile checkout flow. - * - * @access public - * @deprecated No longer used by PayPal. Use Express Checkout instead. - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function SetMobileCheckout($DataArray) - { - $SMCFieldsNVP = '&METHOD=SetMobileCheckout'; - - $SMCFields = isset($DataArray['SMCFields']) ? $DataArray['SMCFields'] : array(); - foreach($SMCFields as $SMCFieldsVar => $SMCFieldsVal) - { - $SMCFieldsNVP .= $SMCFieldsVal != '' ? '&' . strtoupper($SMCFieldsVar) . '=' . urlencode($SMCFieldsVal) : ''; - } - - $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); - foreach($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) - { - $SMCFieldsNVP .= $SMCFieldsVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $SMCFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Finalize and process the sale from a mobile checkout flow. - * - * @access public - * @deprecated No longer used by PayPal. Use Express Checkout instead. - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function DoMobileCheckoutPayment($DataArray) - { - $DMCPFieldsNVP = '&METHOD=DoMobileCheckoutPayment'; - - $DMCPFields = isset($DataArray['DMCPFields']) ? $DataArray['DMCPFields'] : array(); - foreach($DMCPFields as $DMCPFieldsVar => $DMCPFieldsVal) - { - $DMCPFieldsNVP .= $DMCPFieldsVal != '' ? '&' . strtoupper($DMCPFieldsVar) . '=' . urlencode($DMCPFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $DMCPFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Set authorization params - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function SetAuthFlowParam($DataArray) - { - $SetAuthFlowParamFieldsNVP = '&METHOD=SetAuthFlowParam'; - - // SetAuthFlowParam Fields - $SetAuthFlowParamFields = isset($DataArray['SetAuthFlowParamFields']) ? $DataArray['SetAuthFlowParamFields'] : array(); - foreach($SetAuthFlowParamFields as $SetAuthFlowParamFieldsVar => $SetAuthFlowParamFieldsVal) - { - $SetAuthFlowParamFieldsNVP .= $SetAuthFlowParamFieldsVal != '' ? '&' . strtoupper($SetAuthFlowParamFieldsVar) . '=' . urlencode($SetAuthFlowParamFieldsVal) : ''; - } - - // ShippingAddress Fields - $ShippingAddressFields = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); - foreach($ShippingAddressFields as $ShippingAddressFieldsVar => $ShippingAddressFieldsVal) - { - $SetAuthFlowParamFieldsNVP .= $ShippingAddressFieldsVal != '' ? '&' . strtoupper($ShippingAddressFieldsVar) . '=' . urlencode($ShippingAddressFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $SetAuthFlowParamFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - $Token = isset($NVPResponseArray['TOKEN']) ? $NVPResponseArray['TOKEN'] : ''; - $RedirectURL = $Token != '' ? 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_account-authenticate-login&token=' . $Token : ''; - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REDIRECTURL'] = $RedirectURL; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Get authorization details - * - * @access public - * @param string $Token - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetAuthDetails($Token) - { - $GetAuthDetailsFieldsNVP = '&METHOD=GetAuthDetails&TOKEN=' . $Token; - - $NVPRequest = $this->NVPCredentials . $GetAuthDetailsFieldsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - - /** - * Retrieve the current API permissions granted for the application. - * - * @access public - * @deprecated No longer used by PayPal. - * @param string $Token - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function GetAccessPermissionsDetails($Token) - { - $GetAccessPermissionsDetailsNVP = '&METHOD=GetAccessPermissionsDetails&TOKEN=' . $Token; - - $NVPRequest = $this->NVPCredentials . $GetAccessPermissionsDetailsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $Permissions = array(); - $n = 0; - while(isset($NVPResponseArray['L_ACCESSPERMISSIONNAME' . $n . ''])) - { - $LName = isset($NVPResponseArray['L_ACCESSPERMISSIONNAME' . $n . '']) ? $NVPResponseArray['L_ACCESSPERMISSIONNAME' . $n . ''] : ''; - $LStatus = isset($NVPResponseArray['L_ACCESSPERMISSIONSTATUS' . $n . '']) ? $NVPResponseArray['L_ACCESSPERMISSIONSTATUS' . $n . ''] : ''; - - $CurrentItem = array( - 'L_ACCESSPERMISSIONNAME' => $LName, - 'L_ACCESSPERMISSIONSTATUS' => $LStatus - ); - - array_push($ActivePermissions, $CurrentItem); - $n++; - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['Permissions'] = $Permissions; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Set the access permissions for an application on a 3rd party user's account. - * - * @access public - * @deprecated No longer used by PayPal. - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function SetAccessPermissions($DataArray) - { - $SetAccessPermissionsNVP = '&METHOD=SetAccessPermissions'; - - // SetAccessPermissions Fields - $SetAccessPermissionsFields = isset($DataArray['SetAccessPermissionsFields']) ? $DataArray['SetAccessPermissionsFields'] : array(); - foreach($SetAccessPermissionsFields as $SetAccessPermissionsFieldsVar => $SetAccessPermissionsFieldsVal) - { - $SetAccessPermissionsNVP .= $SetAccessPermissionsFieldsVal != '' ? '&' . strtoupper($SetAccessPermissionsFieldsVar) . '=' . urlencode($SetAccessPermissionsFieldsVal) : ''; - } - - $n = 0; - $RequiredPermissions = isset($DataArray['RequiredPermissions']) ? $DataArray['RequiredPermissions'] : array(); - foreach($RequiredPermissions as $RequiredPermission) - { - $SetAccessPermissionsNVP .= '&L_REQUIREDACCESSPERMISSIONS' . $n . '=' . urlencode($RequiredPermission); - $n++; - } - - $n = 0; - $OptionalPermissions = isset($DataArray['OptionalPermissions']) ? $DataArray['OptionalPermissions'] : array(); - foreach($OptionalPermissions as $OptionalPermission) - { - $SetAccessPermissionsNVP .= '&L_OPTIONALACCESSPERMISSIONS' . $n . '=' . urlencode($OptionalPermission); - $n++; - } - - $NVPRequest = $this->NVPCredentials . $SetAccessPermissionsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - $Token = isset($NVPResponseArray['TOKEN']) ? $NVPResponseArray['TOKEN'] : ''; - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - if($this->Sandbox) - { - $RedirectURL = $Token != '' ? 'https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-login&token=' . $Token : ''; - $LogoutRedirectURL = $Token != '' ? 'https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-logout&token=' . $Token : ''; - } - else - { - $RedirectURL = $Token != '' ? 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-login&token=' . $Token : ''; - $LogoutRedirectURL = $Token != '' ? 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-logout&token=' . $Token : ''; - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REDIRECTURL'] = $RedirectURL; - $NVPResponseArray['LOGOUTREDIRECTURL'] = $LogoutRedirectURL; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Update the access permissions for an application on a 3rd party user's account. - * - * @access public - * @deprecated No longer used by PayPal. - * @param string $PayerID Payer ID of the PayPal user. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function UpdateAccessPermissions($PayerID) - { - $UpdateAcccessPermissionsNVP = '&METHOD=UpdateAccessPermissions&PAYERID=' . $PayerID; - - $NVPRequest = $this->NVPCredentials . $UpdateAcccessPermissionsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - - /** - * Obtain a list of your hosted PayPal Payments Standard buttons. - * - * The request contains optional fields that are not currently used. - * All buttons are automatically requested. - * - * @access public - * @param mixed[] $DataArray Array structure of request data. - * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function BMButtonSearch($DataArray) - { - $BMButtonSearchNVP = '&METHOD=BMButtonSearch'; - - // BMButtonSearch Fields - $BMButtonSearchFields = isset($DataArray['BMButtonSearchFields']) ? $DataArray['BMButtonSearchFields'] : array(); - foreach($BMButtonSearchFields as $BMButtonSearchFieldsVar => $BMButtonSearchFieldsVal) - { - $BMButtonSearchNVP .= $BMButtonSearchFieldsVal != '' ? '&' . strtoupper($BMButtonSearchFieldsVar) . '=' . urlencode($BMButtonSearchFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $BMButtonSearchNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $SearchResults = array(); - $n = 0; - while(isset($NVPResponseArray['L_HOSTEDBUTTONID' . $n . ''])) - { - $LHostedButtonID = isset($NVPResponseArray['L_HOSTEDBUTTONID' . $n . '']) ? $NVPResponseArray['L_HOSTEDBUTTONID' . $n . ''] : ''; - $LButtonType = isset($NVPResponseArray['L_BUTTONTYPE' . $n . '']) ? $NVPResponseArray['L_BUTTONTYPE' . $n . ''] : ''; - $LItemName = isset($NVPResponseArray['L_ITEMNAME' . $n . '']) ? $NVPResponseArray['L_ITEMNAME' . $n . ''] : ''; - $LModifyDate = isset($NVPResponseArray['L_MODIFYDATE' . $n . '']) ? $NVPResponseArray['L_MODIFYDATE' . $n . ''] : ''; - - $CurrentItem = array( - 'L_HOSTEDBUTTONID' => $LHostedButtonID, - 'L_BUTTONTYPE' => $LButtonType, - 'L_ITEMNAME' => $LItemName, - 'L_MODIFYDATE' => $LModifyDate - ); - - array_push($SearchResults, $CurrentItem); - $n++; - } - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['SEARCHRESULTS'] = $SearchResults; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Use the BMCreateButton API operation to create a PayPal Payments Standard button. - * You can create either a button that is hosted on PayPal or a non-hosted button. - * - * @param $DataArray - * @return \mixed[] - */ - function BMCreateButton($DataArray) + public function __construct(array $config = []) { - $BMCreateButtonNVP = '&METHOD=BMCreateButton'; - - // BMCreateButton Fields - $BMCreateButtonFields = isset($DataArray['BMCreateButtonFields']) ? $DataArray['BMCreateButtonFields'] : array(); - foreach($BMCreateButtonFields as $BMCreateButtonFieldsVar => $BMCreateButtonFieldsVal) - { - $BMCreateButtonNVP .= $BMCreateButtonFieldsVal != '' ? '&' . strtoupper($BMCreateButtonFieldsVar) . '=' . urlencode($BMCreateButtonFieldsVal) : ''; - } - - $n = 0; - $BMButtonVars = isset($DataArray['BMButtonVars']) ? $DataArray['BMButtonVars'] : array(); - $BMButtonVars['bn'] = $this->APIButtonSource; - foreach($BMButtonVars as $BMButtonVarName => $BMButtonVarValue) - { - $BMCreateButtonNVP .= $BMButtonVarValue != '' ? "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue) : ""; - if($BMButtonVarValue != '') - { - $BMCreateButtonNVP .= "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue); - $n++; - } - } - - $n = 0; - $BMButtonOptions = isset($DataArray['BMButtonOptions']) ? $DataArray['BMButtonOptions'] : array(); - foreach($BMButtonOptions as $BMButtonOption) - { - $n_selection = 0; - - $ButtonOptionName = $BMButtonOption['name']; - $ButtonOptionSelections = $BMButtonOption['selections']; - - $BMCreateButtonNVP .= '&OPTION'. $n . 'NAME=' . $ButtonOptionName; - foreach($ButtonOptionSelections as $ButtonOptionSelection) - { - $BMCreateButtonNVP .= $ButtonOptionSelection['value'] != '' ? '&L_OPTION' . $n . 'SELECT' . $n_selection . '=' . urlencode($ButtonOptionSelection['value']) : ''; - $BMCreateButtonNVP .= $ButtonOptionSelection['price'] != '' ? '&L_OPTION' . $n . 'PRICE' . $n_selection . '=' . urlencode($ButtonOptionSelection['price']) : ''; - $BMCreateButtonNVP .= $ButtonOptionSelection['type'] != '' ? '&L_OPTION' . $n . 'TYPE' . $n_selection . '=' . urlencode($ButtonOptionSelection['type']) : ''; - - $n_selection++; - } - - $n++; - } - - $NVPRequest = $this->NVPCredentials . $BMCreateButtonNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Use the BMUpdateButton API operation to modify a PayPal Payments Standard button that is hosted on PayPal. - * This operation replaces all fields in the specified button; therefore, you must specify a value for - * each field you want to include for the button, whether or not it changed. - * - * @param $DataArray - * @return \mixed[] - */ - function BMUpdateButton($DataArray) - { - $BMUpdateButtonNVP = '&METHOD=BMUpdateButton'; - - // BMUpdateButton Fields - $BMUpdateButtonFields = isset($DataArray['BMUpdateButtonFields']) ? $DataArray['BMUpdateButtonFields'] : array(); - foreach($BMUpdateButtonFields as $BMUpdateButtonFieldsVar => $BMUpdateButtonFieldsVal) - { - $BMUpdateButtonNVP .= $BMUpdateButtonFieldsVal != '' ? '&' . strtoupper($BMUpdateButtonFieldsVar) . '=' . urlencode($BMUpdateButtonFieldsVal) : ''; - } - - $n = 0; - $BMButtonVars = isset($DataArray['BMButtonVars']) ? $DataArray['BMButtonVars'] : array(); - $BMButtonVars['bn'] = $this->APIButtonSource; - foreach($BMButtonVars as $BMButtonVarName => $BMButtonVarValue) - { - $BMUpdateButtonNVP .= $BMButtonVarValue != '' ? "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue) : ""; - if($BMButtonVarValue != '') - { - $BMUpdateButtonNVP .= "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue); - $n++; - } - } - - $n = 0; - $BMButtonOptions = isset($DataArray['BMButtonOptions']) ? $DataArray['BMButtonOptions'] : array(); - foreach($BMButtonOptions as $BMButtonOption) - { - $n_selection = 0; - - $ButtonOptionName = $BMButtonOption['name']; - $ButtonOptionSelections = $BMButtonOption['selections']; - - $BMUpdateButtonNVP .= '&OPTION'. $n . 'NAME=' . $ButtonOptionName; - foreach($ButtonOptionSelections as $ButtonOptionSelection) - { - $BMUpdateButtonNVP .= $ButtonOptionSelection['value'] != '' ? '&L_OPTION' . $n . 'SELECT' . $n_selection . '=' . urlencode($ButtonOptionSelection['value']) : ''; - $BMUpdateButtonNVP .= $ButtonOptionSelection['price'] != '' ? '&L_OPTION' . $n . 'PRICE' . $n_selection . '=' . urlencode($ButtonOptionSelection['price']) : ''; - $BMUpdateButtonNVP .= $ButtonOptionSelection['type'] != '' ? '&L_OPTION' . $n . 'TYPE' . $n_selection . '=' . urlencode($ButtonOptionSelection['type']) : ''; - - $n_selection++; - } - - $n++; - } - - $NVPRequest = $this->NVPCredentials . $BMUpdateButtonNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Use the BMGetButtonDetails API operation to obtain information about a hosted PayPal Payments Standard button. - * You can use this information to set the fields that have not changed when updating a button. - * - * @param $HostedButtonID - * @return mixed[] $NVPResponseArray Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. - */ - function BMGetButtonDetails($HostedButtonID) - { - $BMGetButtonDetailsNVP = '&METHOD=BMGetButtonDetails&HOSTEDBUTTONID=' . $HostedButtonID; - - $NVPRequest = $this->NVPCredentials . $BMGetButtonDetailsNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; + $this->config = $config; + $this->mode = isset($config['Sandbox']) ? $config['Sandbox'] : 'live'; + $this->payPalAPIMode = isset($config['PayPalAPIMode']) ? $config['PayPalAPIMode'] : 'classic'; + $this->Sandbox = ($this->mode === 'sandbox') ? true : false; + $this->LogPath = isset($config['LogPath']) ? $config['LogPath'] : $_SERVER['DOCUMENT_ROOT'].'/logs/'; } /** - * Use the BMGetInventory API operation to determine the inventory levels and other inventory-related - * information for a button and menu items associated with the button. Typically, you call BMGetInventory - * to obtain field values before calling BMSetInventory to change the inventory levels. - * - * @param $DataArray - * @return \mixed[] + * Factory method to instantiate the correct API mode */ - function BMGetInventory($DataArray) + public static function init(array $config = []) { - $BMGetInventoryNVP = '&METHOD=BMGetInventory'; + $apiMode = isset($config['api_mode']) ? $config['api_mode'] : 'classic'; - // BMGetInventory Fields - $BMGetInventoryFields = isset($DataArray['BMGetInventoryFields']) ? $DataArray['BMGetInventoryFields'] : array(); - foreach($BMGetInventoryFields as $BMGetInventoryFieldsVar => $BMGetInventoryFieldsVal) - { - $BMGetInventoryNVP .= $BMGetInventoryFieldsVal != '' ? '&' . strtoupper($BMGetInventoryFieldsVar) . '=' . urlencode($BMGetInventoryFieldsVal) : ''; + switch (strtolower($apiMode)) { + case 'rest': + return new PayPalREST($config); + case 'classic': + return new PayPalClassic($config); + default: + throw new \InvalidArgumentException("Invalid PayPal API mode: $apiMode"); } - - // DigitalDownloadKeys - $n = 0; - $DigitalDownloadKeys = isset($DataArray['DigitalDownloadKeys']) ? $DataArray['DigitalDownloadKeys'] : array(); - foreach($DigitalDownloadKeys as $DigitalDownloadKey) - { - $BMGetInventoryNVP .= '&L_DIGITALDOWNLOADKEYS' . $n . '=' . urlencode($DigitalDownloadKey); - $n++; - } - - $NVPRequest = $this->NVPCredentials . $BMGetInventoryNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - /** - * Use the BMManageButtonStatus API operation to change the status of a hosted button. Currently, you can only delete a button. - * - * @param $DataArray - * @return \mixed[] - */ - function BMManageButtonStatus($DataArray) - { - $BMManageButtonStatusNVP = '&METHOD=BMManageButtonStatus'; - - // BMManageButtonStatus Fields - $BMManageButtonStatusFields = isset($DataArray['BMManageButtonStatusFields']) ? $DataArray['BMManageButtonStatusFields'] : array(); - foreach($BMManageButtonStatusFields as $BMManageButtonStatusFieldsVar => $BMManageButtonStatusFieldsVal) - { - $BMManageButtonStatusNVP .= $BMManageButtonStatusFieldsVal != '' ? '&' . strtoupper($BMManageButtonStatusFieldsVar) . '=' . urlencode($BMManageButtonStatusFieldsVal) : ''; - } - - $NVPRequest = $this->NVPCredentials . $BMManageButtonStatusNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; } /** - * Use the BMSetInventory API operation to set the inventory level and inventory management - * features for the specified button. When you set the inventory level for a button, - * PayPal can track inventory, calculate the gross profit associated with sales, send you - * an alert when inventory drops below a specified quantity, and manage sold out conditions. - * - * @param $DataArray - * @return \mixed[] + * Common interface that both Classic and REST must implement */ - function BMSetInventory($DataArray) - { - $BMSetInventoryNVP = '&METHOD=BMSetInventory'; - - // BMSetInventory Fields - $BMSetInventoryFields = isset($DataArray['BMSetInventoryFields']) ? $DataArray['BMSetInventoryFields'] : array(); - foreach($BMSetInventoryFields as $BMSetInventoryFieldsVar => $BMSetInventoryFieldsVal) - { - $BMSetInventoryNVP .= $BMSetInventoryFieldsVal != '' ? '&' . strtoupper($BMSetInventoryFieldsVar) . '=' . urlencode($BMSetInventoryFieldsVal) : ''; - } - - // DigitalDownloadKeys - $n = 0; - $DigitalDownloadKeys = isset($DataArray['DigitalDownloadKeys']) ? $DataArray['DigitalDownloadKeys'] : array(); - foreach($DigitalDownloadKeys as $DigitalDownloadKey) - { - $BMSetInventoryNVP .= '&L_DIGITALDOWNLOADKEYS' . $n . '=' . urlencode($DigitalDownloadKey); - $n++; - } - - // ItemTrackingDetails - $ItemTrackingDetailsFields = isset($DataArray['ItemTrackingDetails']) ? $DataArray['ItemTrackingDetails'] : array(); - foreach($ItemTrackingDetailsFields as $ItemTrackingDetailsFieldsVar => $ItemTrackingDetailsFieldsVal) - { - $BMSetInventoryNVP .= $ItemTrackingDetailsFieldsVal != '' ? '&' . strtoupper($ItemTrackingDetailsFieldsVar) . '=' . urlencode($ItemTrackingDetailsFieldsVal) : ''; - } - - // OptionTrackingDetails - $n = 0; - $OptionTrackingDetails = isset($DataArray['OptionTrackingDetails']) ? $DataArray['OptionTrackingDetails'] : array(); - foreach($OptionTrackingDetails as $OptionTrackingDetail) - { - $BMSetInventoryNVP .= '&L_OPTIONNUMBER' . $n . '=' . urlencode($OptionTrackingDetail['number']); - $BMSetInventoryNVP .= '&L_OPTIONQTY' . $n . '=' . urlencode($OptionTrackingDetail['qty']); - $BMSetInventoryNVP .= '&L_OPTIONSELECT' . $n . '=' . urlencode($OptionTrackingDetail['select']); - $BMSetInventoryNVP .= '&L_OPTIONQTYDELTA' . $n . '=' . urlencode($OptionTrackingDetail['qtydelta']); - $BMSetInventoryNVP .= '&L_OPTIONALERT' . $n . '=' . urlencode($OptionTrackingDetail['alert']); - $BMSetInventoryNVP .= '&L_OPTIONCOST' . $n . '=' . urlencode($OptionTrackingDetail['cost']); - $n++; - } - - $NVPRequest = $this->NVPCredentials . $BMSetInventoryNVP; - $NVPResponse = $this->CURLRequest($NVPRequest); - $NVPRequestArray = $this->NVPToArray($NVPRequest); - $NVPResponseArray = $this->NVPToArray($NVPResponse); - - $Errors = $this->GetErrors($NVPResponseArray); - - $this->Logger($this->LogPath, __FUNCTION__.'Request', $this->MaskAPIResult($NVPRequest)); - $this->Logger($this->LogPath, __FUNCTION__.'Response', $NVPResponse); - - $NVPResponseArray['ERRORS'] = $Errors; - $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; - $NVPResponseArray['RAWREQUEST'] = $NVPRequest; - $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; - - return $NVPResponseArray; - } - - public function TPV_Parse_Request($result_data, $request_data, $product_id = 1, $sandbox = false, $is_nvp = true, $payment_method = null) { - $request_param = array(); - if (isset($result_data) && is_array($result_data) && !empty($result_data['CURL_ERROR'])) { - return $result_data; - } else { - if ($is_nvp) { - $result = $this->NVPToArray($result_data); - $request = $this->NVPToArray($request_data); - } else { - $result = $result_data; - $request = $request_data; - } - if (is_array($result) && isset($result['PNREF'])) { - $request['METHOD'] = 'ProcessTransaction'; - } - if ($payment_method == 'PayPal_Rest') { - $request['METHOD'] = 'PayPal_Rest'; - } - if (isset($request['METHOD']) && !empty($request['METHOD']) && in_array($request['METHOD'], $this->allow_method)) { - $request_param['site_url'] = ''; - $request_param['merchant_id'] = ''; - $request_param['type'] = $request['METHOD']; - if(is_array($result)) { - $request_param['status'] = isset($result['ACK']) ? $result['ACK'] : ''; - } - $request_param['mode'] = ($sandbox) ? 'sandbox' : 'live'; - $request_param['product_id'] = $product_id; - $request_param['merchant_id'] = ''; - if ($request['METHOD'] == 'DoExpressCheckoutPayment') { - $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; - $request_param['transaction_id'] = isset($result['PAYMENTINFO_0_TRANSACTIONID']) ? $result['PAYMENTINFO_0_TRANSACTIONID'] : ''; - $request_param['amount'] = isset($result['PAYMENTINFO_0_AMT']) ? $result['PAYMENTINFO_0_AMT'] : '0.00'; - $this->TPV_Send_Request($request_param); - } elseif ($request['METHOD'] == 'DoDirectPayment') { - $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; - $request_param['transaction_id'] = isset($result['TRANSACTIONID']) ? $result['TRANSACTIONID'] : ''; - $request_param['amount'] = isset($result['AMT']) ? $result['AMT'] : '0.00'; - $this->TPV_Send_Request($request_param); - } elseif ($request['METHOD'] == 'DoCapture') { - $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; - $request_param['transaction_id'] = isset($result['TRANSACTIONID']) ? $result['TRANSACTIONID'] : ''; - $request_param['amount'] = isset($result['AMT']) ? $result['AMT'] : '0.00'; - $this->TPV_Send_Request($request_param); - } elseif ($request['METHOD'] == 'ProcessTransaction') { - if (isset($result['RESULT']) && ( $result['RESULT'] == 0 )) { - $request_param['status'] = 'Success'; - } else { - $request_param['status'] = 'Failure'; - } - $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; - $request_param['transaction_id'] = isset($result['PNREF']) ? $result['PNREF'] : ''; - $request_param['amount'] = isset($result['AMT']) ? $result['AMT'] : '0.00'; - $this->TPV_Send_Request($request_param); - } elseif ($request['METHOD'] == 'PayPal_Rest') { - $request_param['correlation_id'] = ''; - if( !empty($result->purchase_units[0]['payments']['captures'][0]['amount']['value']) ) { - $request_param['amount'] = $result->purchase_units[0]['payments']['captures'][0]['amount']['value']; - $request_param['status'] = 'Success'; - $request_param['transaction_id'] = $result->purchase_units[0]['payments']['captures'][0]['id']; - } elseif( !empty ($result->purchase_units[0]['payments']['authorizations'][0]['amount']['value'])) { - $request_param['amount'] = $result->purchase_units[0]['payments']['authorizations'][0]['amount']['value']; - $request_param['status'] = 'Success'; - $request_param['transaction_id'] = $result->purchase_units[0]['payments']['authorizations'][0]['id']; - } elseif( !empty ($result['id']) ) { - $request_param['amount'] = !empty($result['transactions'][0]['amount']['total']) ? $result['transactions'][0]['amount']['total'] : ''; - $request_param['status'] = 'Success'; - $request_param['transaction_id'] = isset($result['transactions'][0]['related_resources'][0]['sale']['id']) ? $result['transactions'][0]['related_resources'][0]['sale']['id'] : ''; - } else { - $request_param['status'] = 'Failure'; - } - $this->TPV_Send_Request($request_param); - } - } - } - return $result_data; - } - - function TPV_Send_Request($request_param) { - try { - $payment_type = $request_param['type']; - $amount = $request_param['amount']; - $status = $request_param['status']; - $site_url = $request_param['site_url']; - $payment_mode = $request_param['mode']; - $merchant_id = $request_param['merchant_id']; - $correlation_id = $request_param['correlation_id']; - $transaction_id = $request_param['transaction_id']; - $product_id = $request_param['product_id']; - $params = [ - "product_id" => $product_id, - "type" => $payment_type, - "amount" => $amount, - "status" => $status, - "site_url" => $site_url, - "mode" => $payment_mode, - "merchant_id" => $merchant_id, - "correlation_id" => $correlation_id, - "transaction_id" => $transaction_id - ]; - $curl = curl_init(); - curl_setopt($curl, CURLOPT_HTTPHEADER, array( - 'Content-Type: application/json; charset=utf-8', - 'x-api-key: ' . $this->api_key, - 'Content-Length: ' . strlen(json_encode($params)) - )); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_URL, $this->api_url); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params)); - curl_exec($curl); - } catch (Exception $ex) { - - } - } - +// abstract public function SetExpressCheckout(array $params); +// abstract public function GetExpressCheckoutDetails($token); +// abstract public function DoExpressCheckoutPayment(array $params); +// abstract public function DoCapture(array $params); +// abstract public function DoAuthorization(array $params); +// abstract public function DoVoid(array $params); +// abstract public function DoDirectPayment(array $params); +// abstract public function RefundTransaction(array $params); +// abstract public function orderData(array $params); +// abstract public function getOrder(int $orderID); +// abstract public function authorizeOrder(int $orderID); +// abstract public function captureOrder(int $orderID); } \ No newline at end of file diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php index 328f4352..53b61cad 100644 --- a/src/angelleye/PayPal/PayPalREST.php +++ b/src/angelleye/PayPal/PayPalREST.php @@ -1,251 +1,414 @@ baseUrl = $this->mode === 'sandbox' + // Override base URL for REST API endpoints + $this->base_url = $this->Sandbox ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com'; + + // Set REST-specific credentials + $this->client_id = isset($config['ClientID']) ? $config['ClientID'] : ''; + $this->client_secret = isset($config['ClientSecret']) ? $config['ClientSecret'] : ''; + + // Parent class already handles: sandbox, print_headers, log_results, log_path, base URLs + } + + /** + * Test method to verify class instantiation + */ + public function test() + { + return [ + 'success' => true, + 'message' => 'PayPalREST class initialized successfully', + 'base_url' => $this->base_url, // Now matches the property + 'mode' => $this->Sandbox // Now this exists + ]; + } + + /** + * Get standard headers for API requests + */ + private function getHeaders($includeAuth = true, $contentType = 'application/json') + { + $headers = [ + 'Content-Type: ' . $contentType, + 'Accept: application/json', + 'Partner-Attribution-Id: AngellEYELLC_Ecom_PHPCatalog' + ]; + + if ($includeAuth) { + $token = $this->getAccessToken(); + $headers[] = 'Authorization: Bearer ' . $token; + } + + return $headers; + } + + /** + * Get OAuth-specific headers (for token requests) + */ + private function getOAuthHeaders() + { + $auth = base64_encode($this->client_id . ':' . $this->client_secret); + + return [ + 'Authorization: Basic ' . $auth, + 'Content-Type: application/x-www-form-urlencoded', + 'Accept: application/json', + 'Partner-Attribution-Id: AngellEYELLC_Ecom_PHPCatalog' + ]; } /** * Get OAuth 2.0 access token + * Caches token for 9 hours to avoid redundant API calls */ - protected function getAccessToken() { - // Return cached token if still valid + private function getAccessToken() + { + // Check if we have a valid cached token if ($this->accessToken && $this->tokenExpiry > time()) { return $this->accessToken; } - $url = $this->baseUrl . '/v1/oauth2/token'; - $credentials = base64_encode( - $this->config['rest']['client_id'] . ':' . - $this->config['rest']['client_secret'] - ); + $auth = base64_encode($this->client_id . ':' . $this->client_secret); - $headers = [ - 'Authorization: Basic ' . $credentials, - 'Content-Type: application/x-www-form-urlencoded', - 'PayPal-Request-Id: ' . $this->generateRequestId() - ]; + $headers = $this->getOAuthHeaders(); + $postData = 'grant_type=client_credentials'; - try { - $ch = curl_init(); - curl_setopt_array($ch, [ - CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => 'grant_type=client_credentials', - CURLOPT_HTTPHEADER => $headers, - CURLOPT_SSL_VERIFYPEER => true, - CURLOPT_SSL_VERIFYHOST => 2 - ]); - - $response = curl_exec($ch); - $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - if (curl_errno($ch)) { - throw new \Exception('cURL error: ' . curl_error($ch)); - } + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $this->base_url . '/v1/oauth2/token'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - curl_close($ch); - $responseData = json_decode($response, true); + $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); - if ($httpCode >= 400) { - throw new \Exception( - "OAuth Error: " . ($responseData['error_description'] ?? 'Unknown error') - ); - } + if ($httpCode === 200) { + $data = json_decode($response, true); + $this->accessToken = $data['access_token']; + // Set expiry with 1 minute buffer (9 hours - 1 minute) + $this->tokenExpiry = time() + ($data['expires_in'] - 60); - $this->accessToken = $responseData['access_token']; - $this->tokenExpiry = time() + $responseData['expires_in'] - 60; return $this->accessToken; - - } catch (\Exception $e) { - $this->log->error('OAuth Error: ' . $e->getMessage()); - throw $e; } + + throw new \Exception('Failed to get OAuth token: ' . $response); } /** - * Make REST API request with OAuth + * Make authenticated REST API request */ - protected function makeRestRequest($endpoint, $method, $data = null, $additionalHeaders = []) { - $headers = array_merge([ - 'Authorization: Bearer ' . $this->getAccessToken(), - 'Content-Type: application/json', - 'PayPal-Request-Id: ' . $this->generateRequestId() - ], $additionalHeaders); + protected function makeRequest($endpoint, $method = 'GET', $data = null) + { + $token = $this->getAccessToken(); - try { - $ch = curl_init(); - curl_setopt_array($ch, [ - CURLOPT_URL => $this->baseUrl . $endpoint, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_HTTPHEADER => $headers, - CURLOPT_SSL_VERIFYPEER => true, - CURLOPT_SSL_VERIFYHOST => 2 - ]); - - if ($method === 'POST') { - curl_setopt($ch, CURLOPT_POST, true); - if ($data) { - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); - } - } + $headers = $this->getHeaders(true); - $response = curl_exec($ch); - $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $this->base_url . $endpoint); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - if (curl_errno($ch)) { - throw new \Exception('cURL error: ' . curl_error($ch)); - } + if ($data && ($method === 'POST' || $method === 'PUT' || $method === 'PATCH')) { + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); + } - curl_close($ch); - $responseData = json_decode($response, true); + $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); - if ($httpCode >= 400) { - $this->handleRestError($responseData); - } - - return $responseData; + return [ + 'status_code' => $httpCode, + 'body' => json_decode($response, true), + 'raw_response' => $response + ]; + } + /** + * Test OAuth authentication + */ + public function testOAuth() + { + try { + $token = $this->getAccessToken(); + return [ + 'success' => true, + 'message' => 'OAuth token retrieved successfully', + 'token_preview' => substr($token, 0, 20) . '...', + 'expires_in' => $this->tokenExpiry - time() + ]; } catch (\Exception $e) { - $this->log->error('REST API Error: ' . $e->getMessage()); - throw $e; + return [ + 'success' => false, + 'message' => 'OAuth failed: ' . $e->getMessage() + ]; } } /** - * Handle REST API errors + * Test simple API call (get webhook list - minimal permissions needed) */ - protected function handleRestError($response) { - $message = isset($response['message']) ? $response['message'] : 'Unknown error'; - $debug_id = isset($response['debug_id']) ? $response['debug_id'] : ''; - - $this->log->error("PayPal REST Error: $message (Debug ID: $debug_id)"); - throw new \Exception("PayPal REST Error: $message (Debug ID: $debug_id)"); + public function testAPICall() + { + try { + $response = $this->makeRequest('/v1/notifications/webhooks'); + return [ + 'success' => $response['status_code'] >= 200 && $response['status_code'] < 300, + 'message' => $response['status_code'] >= 200 && $response['status_code'] < 300 + ? 'API call successful' + : 'API call failed', + 'status_code' => $response['status_code'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'message' => 'API call failed: ' . $e->getMessage(), + 'status_code' => 0 + ]; + } } /** - * Generate unique request ID + * Create an order (replaces SetExpressCheckout) */ - protected function generateRequestId() { - return vsprintf('%s%s-%s-4000-8000-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)); + public function createOrder($orderData) + { + try { + $response = $this->makeRequest('/v2/checkout/orders', 'POST', $orderData); + + if ($response['status_code'] === 201) { + return [ + 'success' => true, + 'order_id' => $response['body']['id'], + 'status' => $response['body']['status'], + 'approval_url' => $this->getApprovalUrl($response['body']['links']), + 'full_response' => $response['body'] + ]; + } + + return [ + 'success' => false, + 'error' => 'Failed to create order', + 'status_code' => $response['status_code'], + 'details' => $response['body'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } } /** - * SetExpressCheckout implementation using REST API + * Get order details (replaces GetExpressCheckoutDetails) */ - public function SetExpressCheckout($params) { - // Map classic params to REST format - $orderData = [ - 'intent' => isset($params['PAYMENTREQUEST_0_PAYMENTACTION']) && - $params['PAYMENTREQUEST_0_PAYMENTACTION'] === 'Authorization' - ? 'AUTHORIZE' : 'CAPTURE', - 'purchase_units' => [ - [ - 'amount' => [ - 'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD', - 'value' => $params['PAYMENTREQUEST_0_AMT'] ?? '0.00' - ] - ] - ], - 'payment_source' => [ - 'paypal' => [ - 'experience_context' => [ - 'return_url' => $params['RETURNURL'], - 'cancel_url' => $params['CANCELURL'], - 'brand_name' => $params['BRANDNAME'] ?? null, - 'locale' => $params['LOCALECODE'] ?? 'en-US', - 'shipping_preference' => $this->mapShippingPreference($params) - ] - ] - ] - ]; + public function getOrder($orderId) + { + try { + $response = $this->makeRequest('/v2/checkout/orders/' . $orderId, 'GET'); - // Add items if present - if (isset($params['L_PAYMENTREQUEST_0_NAME0'])) { - $orderData['purchase_units'][0]['items'] = $this->mapLineItems($params); - $orderData['purchase_units'][0]['amount']['breakdown'] = $this->mapAmountBreakdown($params); - } + if ($response['status_code'] === 200) { + return [ + 'success' => true, + 'order' => $response['body'] + ]; + } - // Add billing agreement details if present - if (isset($params['L_BILLINGTYPE0'])) { - $orderData = $this->addBillingAgreementDetails($orderData, $params); + return [ + 'success' => false, + 'error' => 'Failed to get order details', + 'status_code' => $response['status_code'], + 'details' => $response['body'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; } - - $response = $this->makeRestRequest('/v2/checkout/orders', 'POST', $orderData); - - // Return in classic format - return $this->formatOrderResponse($response); } /** - * Map shipping preference from classic to REST + * Authorize order (for auth-only transactions) */ - protected function mapShippingPreference($params) { - if (isset($params['NOSHIPPING']) && $params['NOSHIPPING'] === '1') { - return 'NO_SHIPPING'; - } - if (isset($params['ADDROVERRIDE']) && $params['ADDROVERRIDE'] === '1') { - return 'SET_PROVIDED_ADDRESS'; + public function authorizeOrder($orderId) + { + try { + $response = $this->makeRequest('/v2/checkout/orders/' . $orderId . '/authorize', 'POST'); + + if ($response['status_code'] === 201) { + return [ + 'success' => true, + 'authorization_id' => $response['body']['purchase_units'][0]['payments']['authorizations'][0]['id'], + 'status' => $response['body']['status'], + 'full_response' => $response['body'] + ]; + } + + return [ + 'success' => false, + 'error' => 'Failed to authorize order', + 'status_code' => $response['status_code'], + 'details' => $response['body'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; } - return 'GET_FROM_FILE'; } /** - * Map line items from classic to REST + * Capture order (replaces DoExpressCheckoutPayment) */ - protected function mapLineItems($params) { - $items = []; - $i = 0; - while (isset($params["L_PAYMENTREQUEST_0_NAME$i"])) { - $items[] = [ - 'name' => $params["L_PAYMENTREQUEST_0_NAME$i"], - 'quantity' => $params["L_PAYMENTREQUEST_0_QTY$i"] ?? 1, - 'unit_amount' => [ - 'currency_code' => $params['PAYMENTREQUEST_0_CURRENCYCODE'] ?? 'USD', - 'value' => $params["L_PAYMENTREQUEST_0_AMT$i"] - ], - 'description' => $params["L_PAYMENTREQUEST_0_DESC$i"] ?? null, - 'sku' => $params["L_PAYMENTREQUEST_0_NUMBER$i"] ?? null + public function captureOrder($orderId) + { + try { + $response = $this->makeRequest('/v2/checkout/orders/' . $orderId . '/capture', 'POST'); + + if ($response['status_code'] === 201) { + return [ + 'success' => true, + 'capture_id' => $response['body']['purchase_units'][0]['payments']['captures'][0]['id'], + 'status' => $response['body']['status'], + 'full_response' => $response['body'] + ]; + } + + return [ + 'success' => false, + 'error' => 'Failed to capture order', + 'status_code' => $response['status_code'], + 'details' => $response['body'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() ]; - $i++; } - return $items; } /** - * Format REST response to match classic API + * Helper method to extract approval URL from links */ - protected function formatOrderResponse($response) { - $result = [ - 'TOKEN' => $response['id'], - 'TIMESTAMP' => date('Y-m-d\TH:i:s\Z'), - 'ACK' => 'Success' - ]; - - foreach ($response['links'] as $link) { + private function getApprovalUrl($links) + { + foreach ($links as $link) { if ($link['rel'] === 'approve') { - $result['REDIRECTURL'] = $link['href']; - break; + return $link['href']; } } + return null; + } + + /** + * Test Orders API functionality + */ + public function testOrdersAPI() + { + try { + // Test data for creating an order + $orderData = [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ + [ + 'amount' => [ + 'currency_code' => 'USD', + 'value' => '10.00' + ], + 'description' => 'Test order from PayPalREST class' + ] + ], + 'application_context' => [ + 'return_url' => 'https://example.com/return', + 'cancel_url' => 'https://example.com/cancel' + ] + ]; + + echo "

Step 1: Creating Order...

"; + $createResult = $this->createOrder($orderData); + + if (!$createResult['success']) { + return [ + 'success' => false, + 'step_failed' => 'create_order', + 'error' => $createResult['error'] + ]; + } - return $result; + $orderId = $createResult['order_id']; + echo "Order Created Successfully
"; + echo "Order ID: " . $orderId . "
"; + echo "Status: " . $createResult['status'] . "
"; + echo "Approval URL: " . $createResult['approval_url'] . "

"; + + // Test getting order details + echo "

Step 2: Getting Order Details...

"; + $getResult = $this->getOrder($orderId); + + if (!$getResult['success']) { + return [ + 'success' => false, + 'step_failed' => 'get_order', + 'error' => $getResult['error'], + 'order_id' => $orderId + ]; + } + + echo "Order Details Retrieved Successfully
"; + echo "Order Status: " . $getResult['order']['status'] . "
"; + echo "Order Amount: " . $getResult['order']['purchase_units'][0]['amount']['value'] . " " . + $getResult['order']['purchase_units'][0]['amount']['currency_code'] . "

"; + + return [ + 'success' => true, + 'message' => 'Orders API test completed successfully', + 'order_id' => $orderId, + 'create_result' => $createResult, + 'get_result' => $getResult + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => 'Orders API test failed: ' . $e->getMessage() + ]; + } } - // Additional methods would follow similar pattern... + // REST-specific methods will go here + // OAuth, HTTP requests, etc. } \ No newline at end of file From 17e06f66e2bd20d4d3e4a3c2fdf1ce3a6ba6694d Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Thu, 9 Oct 2025 16:42:29 +0530 Subject: [PATCH 008/146] Missing File Added --- samples/rest/GetBalance.php | 28 + src/angelleye/PayPal/PayPalClassic.php | 3270 ++++++++++++++++++++++++ 2 files changed, 3298 insertions(+) create mode 100644 samples/rest/GetBalance.php create mode 100644 src/angelleye/PayPal/PayPalClassic.php diff --git a/samples/rest/GetBalance.php b/samples/rest/GetBalance.php new file mode 100644 index 00000000..6936cc9c --- /dev/null +++ b/samples/rest/GetBalance.php @@ -0,0 +1,28 @@ + $sandbox, + 'APIMode' => $api_mode, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + ); + +$PayPal = new angelleye\PayPal\PayPal($PayPalConfig); + +// Prepare request arrays +$GBFields = array('returnallcurrencies' => ''); +$PayPalRequestData = array('GBFields'=>$GBFields); + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$PayPalResult = $PayPal->GetBalance($PayPalRequestData); + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
new file mode 100644
index 00000000..0247c27a
--- /dev/null
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -0,0 +1,3270 @@
+
+ *
+ * @package         paypal-php-library
+ * @author          Andrew Angell 
+ * @link            https://github.com/angelleye/paypal-php-library/
+ * @website         http://www.angelleye.com
+ * @support         http://www.angelleye.com/product/premium-support/
+ * @version         v3.0.5
+ * @filesource
+*/
+
+/**
+ * PayPal Classic Class
+ *
+ * This is the parent PayPal class that all child classes extend.
+ *
+ * @package         paypal-php-library
+ * @author          Andrew Angell 
+ */
+class PayPalClassic extends PayPal
+{
+    var $APIUsername = '';
+    var $APIPassword = '';
+    var $APISignature = '';
+    var $APISubject = '';
+    var $APIVersion = '';
+    var $APIButtonSource = '';
+    var $APIMode = '';
+    var $EndPointURL = '';
+    var $PathToCertKeyPEM = '';
+    var $SSL = '';
+    var $PrintHeaders = '';
+    var $LogResults = '';
+    private string $api_url;
+    private string $api_key;
+/**
+     * @var array|string[]
+     */
+    private array $allow_method;
+    protected bool $Sandbox = true;
+    protected string $payPalAPIMode = '';
+    protected ?string $LogPath = null;
+    protected string $NVPCredentials;
+    protected array $Countries;
+    protected array $States;
+    protected array $AVSCodes;
+    protected array $CVV2Codes;
+    protected array $CurrencyCodes;
+/**
+     * Constructor
+     *
+     * @access  public
+     * @param   mixed[] $DataArray  Array structure providing config data
+     * @return  void
+     */
+    function __construct($DataArray)
+    {
+        if (isset($DataArray['Sandbox'])) {
+            $this->Sandbox = $DataArray['Sandbox'];
+        } else {
+            $this->Sandbox = true;
+        }
+
+        // abstract public function SetExpressCheckout(array $params);
+        // abstract public function GetExpressCheckoutDetails($token);
+        // abstract public function DoExpressCheckoutPayment(array $params);
+        // abstract public function DoCapture(array $params);
+        // abstract public function DoAuthorization(array $params);
+        // abstract public function DoVoid(array $params);
+        // abstract public function DoDirectPayment(array $params);
+        // abstract public function RefundTransaction(array $params);
+
+        $this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0';
+        $this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature';
+        $this->payPalAPIMode = isset($DataArray['payPalAPIMode']) ? $DataArray['payPalAPIMode'] : 'classic';
+        $this->APIButtonSource = 'AngellEYELLC_Ecom_PHPCatalog';
+        $this->PathToCertKeyPEM = '/path/to/cert/pem.txt';
+        $this->SSL = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? true : false;
+        $this->APISubject = isset($DataArray['APISubject']) ? $DataArray['APISubject'] : '';
+        $this->PrintHeaders = isset($DataArray['PrintHeaders']) ? $DataArray['PrintHeaders'] : false;
+        $this->LogResults = isset($DataArray['LogResults']) ? $DataArray['LogResults'] : false;
+        $this->LogPath = isset($DataArray['LogPath']) ? $DataArray['LogPath'] : '/logs/';
+        $this->api_url = 'https://gtctgyk7fh.execute-api.us-east-2.amazonaws.com/default/PayPalPaymentsTracker';
+        $this->api_key = 'srGiuJFpDO4W7YCDXF56g2c9nT1JhlURVGqYD7oa';
+        $this->allow_method = array('DoExpressCheckoutPayment', 'DoDirectPayment', 'DoCapture', 'ProcessTransaction', 'PayPal_Rest');
+        if ($this->Sandbox) {
+        // Show Errors
+            error_reporting(E_ALL);
+            ini_set('display_errors', '1');
+
+            # Sandbox
+            $this->APIUsername = isset($DataArray['APIUsername']) && $DataArray['APIUsername'] != '' ? $DataArray['APIUsername'] : '';
+            $this->APIPassword = isset($DataArray['APIPassword']) && $DataArray['APIPassword'] != '' ? $DataArray['APIPassword'] : '';
+            $this->APISignature = isset($DataArray['APISignature']) && $DataArray['APISignature'] != '' ? $DataArray['APISignature'] : '';
+            $this->EndPointURL = isset($DataArray['EndPointURL']) && $DataArray['EndPointURL'] != '' ? $DataArray['EndPointURL'] : 'https://api-3t.sandbox.paypal.com/nvp';
+        } else {
+            $this->APIUsername = isset($DataArray['APIUsername']) && $DataArray['APIUsername'] != '' ? $DataArray['APIUsername'] : '';
+            $this->APIPassword = isset($DataArray['APIPassword']) && $DataArray['APIPassword'] != '' ? $DataArray['APIPassword'] : '';
+            $this->APISignature = isset($DataArray['APISignature']) && $DataArray['APISignature'] != '' ? $DataArray['APISignature'] : '';
+            $this->EndPointURL = isset($DataArray['EndPointURL']) && $DataArray['EndPointURL'] != ''  ? $DataArray['EndPointURL'] : 'https://api-3t.paypal.com/nvp';
+        }
+
+        // Create the NVP credentials string which is required in all calls.
+        $this->NVPCredentials = 'USER=' . $this->APIUsername . '&PWD=' . $this->APIPassword . '&VERSION=' . $this->APIVersion . '&BUTTONSOURCE=' . $this->APIButtonSource;
+        $this->NVPCredentials .= $this->APISubject != '' ? '&SUBJECT=' . $this->APISubject : '';
+        $this->NVPCredentials .= $this->APIMode == 'Signature' ? '&SIGNATURE=' . $this->APISignature : '';
+
+        $this->Countries = array(
+                            'Afghanistan' => 'AF',
+                            'ÌÉland Islands' => 'AX',
+                            'Albania' => 'AL',
+                            'Algeria' => 'DZ',
+                            'American Samoa' => 'AS',
+                            'Andorra' => 'AD',
+                            'Angola' => 'AO',
+                            'Anguilla' => 'AI',
+                            'Antarctica' => 'AQ',
+                            'Antigua and Barbuda' => 'AG',
+                            'Argentina' => 'AR',
+                            'Armenia' => 'AM',
+                            'Aruba' => 'AW',
+                            'Australia' => 'AU',
+                            'Austria' => 'AT',
+                            'Azerbaijan' => 'AZ',
+                            'Bahamas' => 'BS',
+                            'Bahrain' => 'BH',
+                            'Bangladesh' => 'BD',
+                            'Barbados' => 'BB',
+                            'Belarus' => 'BY',
+                            'Belgium' => 'BE',
+                            'Belize' => 'BZ',
+                            'Benin' => 'BJ',
+                            'Bermuda' => 'BM',
+                            'Bhutan' => 'BT',
+                            'Bolivia' => 'BO',
+                            'Bosnia and Herzegovina' => 'BA',
+                            'Botswana' => 'BW',
+                            'Bouvet Island' => 'BV',
+                            'Brazil' => 'BR',
+                            'British Indian Ocean Territory' => 'IO',
+                            'Brunei Darussalam' => 'BN',
+                            'Bulgaria' => 'BG',
+                            'Burkina Faso' => 'BF',
+                            'Burundi' => 'BI',
+                            'Cambodia' => 'KH',
+                            'Cameroon' => 'CM',
+                            'Canada' => 'CA',
+                            'Cape Verde' => 'CV',
+                            'Cayman Islands' => 'KY',
+                            'Central African Republic' => 'CF',
+                            'Chad' => 'TD',
+                            'Chile' => 'CL',
+                            'China' => 'CN',
+                            'Christmas Island' => 'CX',
+                            'Cocos (Keeling) Islands' => 'CC',
+                            'Colombia' => 'CO',
+                            'Comoros' => 'KM',
+                            'Congo' => 'CG',
+                            'Congo, The Democratic Republic of the' => 'CD',
+                            'Cook Islands' => 'CK',
+                            'Costa Rica' => 'CR',
+                            "Cote D'Ivoire" => 'CI',
+                            'Croatia' => 'HR',
+                            'Cuba' => 'CU',
+                            'Cyprus' => 'CY',
+                            'Czech Republic' => 'CZ',
+                            'Denmark' => 'DK',
+                            'Djibouti' => 'DJ',
+                            'Dominica' => 'DM',
+                            'Dominican Republic' => 'DO',
+                            'Ecuador' => 'EC',
+                            'Egypt' => 'EG',
+                            'El Salvador' => 'SV',
+                            'Equatorial Guinea' => 'GQ',
+                            'Eritrea' => 'ER',
+                            'Estonia' => 'EE',
+                            'Ethiopia' => 'ET',
+                            'Falkland Islands (Malvinas)' => 'FK',
+                            'Faroe Islands' => 'FO',
+                            'Fiji' => 'FJ',
+                            'Finland' => 'FI',
+                            'France' => 'FR',
+                            'French Guiana' => 'GF',
+                            'French Polynesia' => 'PF',
+                            'French Southern Territories' => 'TF',
+                            'Gabon' => 'GA',
+                            'Gambia' => 'GM',
+                            'Georgia' => 'GE',
+                            'Germany' => 'DE',
+                            'Ghana' => 'GH',
+                            'Gibraltar' => 'GI',
+                            'Greece' => 'GR',
+                            'Greenland' => 'GL',
+                            'Grenada' => 'GD',
+                            'Guadeloupe' => 'GP',
+                            'Guam' => 'GU',
+                            'Guatemala' => 'GT',
+                            'Guernsey' => 'GG',
+                            'Guinea' => 'GN',
+                            'Guinea-Bissau' => 'GW',
+                            'Guyana' => 'GY',
+                            'Haiti' => 'HT',
+                            'Heard Island and McDonald Islands' => 'HM',
+                            'Holy See (Vatican City State)' => 'VA',
+                            'Honduras' => 'HN',
+                            'Hong Kong' => 'HK',
+                            'Hungary' => 'HU',
+                            'Iceland' => 'IS',
+                            'India' => 'IN',
+                            'Indonesia' => 'ID',
+                            'Iran, Islamic Republic of' => 'IR',
+                            'Iraq' => 'IQ',
+                            'Ireland' => 'IE',
+                            'Isle of Man' => 'IM',
+                            'Israel' => 'IL',
+                            'Italy' => 'IT',
+                            'Jamaica' => 'JM',
+                            'Japan' => 'JP',
+                            'Jersey' => 'JE',
+                            'Jordan' => 'JO',
+                            'Kazakhstan' => 'KZ',
+                            'Kenya' => 'KE',
+                            'Kiribati' => 'KI',
+                            "Korea, Democratic People's Republic of" => 'KP',
+                            'Korea, Republic of' => 'KR',
+                            'Kuwait' => 'KW',
+                            'Kyrgyzstan' => 'KG',
+                            "Laos People's Democratic Republic" => 'LA',
+                            'Latvia' => 'LV',
+                            'Lebanon' => 'LB',
+                            'Lesotho' => 'LS',
+                            'Liberia' => 'LR',
+                            'Libyan Arab Jamahiriya' => 'LY',
+                            'Liechtenstein' => 'LI',
+                            'Lithuania' => 'LT',
+                            'Luxembourg' => 'LU',
+                            'Macao' => 'MO',
+                            'Macedonia, The former Yugoslav Republic of' => 'MK',
+                            'Madagascar' => 'MG',
+                            'Malawi' => 'MW',
+                            'Malaysia' => 'MY',
+                            'Maldives' => 'MV',
+                            'Mali' => 'ML',
+                            'Malta' => 'MT',
+                            'Marshall Islands' => 'MH',
+                            'Martinique' => 'MQ',
+                            'Mauritania' => 'MR',
+                            'Mauritius' => 'MU',
+                            'Mayotte' => 'YT',
+                            'Mexico' => 'MX',
+                            'Micronesia, Federated States of' => 'FM',
+                            'Moldova, Republic of' => 'MD',
+                            'Monaco' => 'MC',
+                            'Mongolia' => 'MN',
+                            'Montserrat' => 'MS',
+                            'Morocco' => 'MA',
+                            'Mozambique' => 'MZ',
+                            'Myanmar' => 'MM',
+                            'Namibia' => 'NA',
+                            'Nauru' => 'NR',
+                            'Nepal' => 'NP',
+                            'Netherlands' => 'NL',
+                            'Netherlands Antilles' => 'AN',
+                            'New Caledonia' => 'NC',
+                            'New Zealand' => 'NZ',
+                            'Nicaragua' => 'NI',
+                            'Niger' => 'NE',
+                            'Nigeria' => 'NG',
+                            'Niue' => 'NU',
+                            'Norfolk Island' => 'NF',
+                            'Northern Mariana Islands' => 'MP',
+                            'Norway' => 'NO',
+                            'Oman' => 'OM',
+                            'Pakistan' => 'PK',
+                            'Palau' => 'PW',
+                            'Palestinian Territory, Occupied' => 'PS',
+                            'Panama' => 'PA',
+                            'Papua New Guinea' => 'PG',
+                            'Paraguay' => 'PY',
+                            'Peru' => 'PE',
+                            'Philippines' => 'PH',
+                            'Pitcairn' => 'PN',
+                            'Poland' => 'PL',
+                            'Portugal' => 'PT',
+                            'Puerto Rico' => 'PR',
+                            'Qatar' => 'QA',
+                            'Reunion' => 'RE',
+                            'Romania' => 'RO',
+                            'Russian Federation' => 'RU',
+                            'Rwanda' => 'RW',
+                            'Saint Helena' => 'SH',
+                            'Saint Kitts and Nevis' => 'KN',
+                            'Saint Lucia' => 'LC',
+                            'Saint Pierre and Miquelon' => 'PM',
+                            'Saint Vincent and the Grenadines' => 'VC',
+                            'Samoa' => 'WS',
+                            'San Marino' => 'SM',
+                            'Sao Tome and Principe' => 'ST',
+                            'Saudi Arabia' => 'SA',
+                            'Senegal' => 'SN',
+                            'Serbia and Montenegro' => 'CS',
+                            'Seychelles' => 'SC',
+                            'Sierra Leone' => 'SL',
+                            'Singapore' => 'SG',
+                            'Slovakia' => 'SK',
+                            'Slovenia' => 'SI',
+                            'Solomon Islands' => 'SB',
+                            'Somalia' => 'SO',
+                            'South Africa' => 'ZA',
+                            'South Georgia and the South Sandwich Islands' => 'GS',
+                            'Spain' => 'ES',
+                            'Sri Lanka' => 'LK',
+                            'Sudan' => 'SD',
+                            'Suriname' => 'SR',
+                            'SValbard and Jan Mayen' => 'SJ',
+                            'Swaziland' => 'SZ',
+                            'Sweden' => 'SE',
+                            'Switzerland' => 'CH',
+                            'Syrian Arab Republic' => 'SY',
+                            'Taiwan, Province of China' => 'TW',
+                            'Tajikistan' => 'TJ',
+                            'Tanzania, United Republic of' => 'TZ',
+                            'Thailand' => 'TH',
+                            'Timor-Leste' => 'TL',
+                            'Togo' => 'TG',
+                            'Tokelau' => 'TK',
+                            'Tonga' => 'TO',
+                            'Trinidad and Tobago' => 'TT',
+                            'Tunisia' => 'TN',
+                            'Turkey' => 'TR',
+                            'Turkmenistan' => 'TM',
+                            'Turks and Caicos Islands' => 'TC',
+                            'Tuvalu' => 'TV',
+                            'Uganda' => 'UG',
+                            'Ukraine' => 'UA',
+                            'United Arab Emirates' => 'AE',
+                            'United Kingdom' => 'GB',
+                            'United States' => 'US',
+                            'United States Minor Outlying Islands' => 'UM',
+                            'Uruguay' => 'UY',
+                            'Uzbekistan' => 'UZ',
+                            'Vanuatu' => 'VU',
+                            'Venezuela' => 'VE',
+                            'Viet Nam' => 'VN',
+                            'Virgin Islands, British' => 'VG',
+                            'Virgin Islands, U.S.' => 'VI',
+                            'Wallis and Futuna' => 'WF',
+                            'Western Sahara' => 'EH',
+                            'Yemen' => 'YE',
+                            'Zambia' => 'ZM',
+                            'Zimbabwe' => 'ZW');
+
+        $this->States = array(
+                        'Alberta' => 'AB',
+                        'British Columbia' => 'BC',
+                        'Manitoba' => 'MB',
+                        'New Brunswick' => 'NB',
+                        'Newfoundland and Labrador' => 'NF',
+                        'Northwest Territories' => 'NT',
+                        'Nova Scotia' => 'NS',
+                        'Nunavut' => 'NU',
+                        'Ontario' => 'ON',
+                        'Prince Edward Island' => 'PE',
+                        'Quebec' => 'QC',
+                        'Saskatchewan' => 'SK',
+                        'Yukon' => 'YK',
+                        'Alabama' => 'AL',
+                        'Alaska' => 'AK',
+                        'American Samoa' => 'AS',
+                        'Arizona' => 'AZ',
+                        'Arkansas' => 'AR',
+                        'California' => 'CA',
+                        'Colorado' => 'CO',
+                        'Connecticut' => 'CT',
+                        'Delaware' => 'DE',
+                        'District of Columbia' => 'DC',
+                        'Federated States of Micronesia' => 'FM',
+                        'Florida' => 'FL',
+                        'Georgia' => 'GA',
+                        'Guam' => 'GU',
+                        'Hawaii' => 'HI',
+                        'Idaho' => 'ID',
+                        'Illinois' => 'IL',
+                        'Indiana' => 'IN',
+                        'Iowa' => 'IA',
+                        'Kansas' => 'KS',
+                        'Kentucky' => 'KY',
+                        'Louisiana' => 'LA',
+                        'Maine' => 'ME',
+                        'Marshall Islands' => 'MH',
+                        'Maryland' => 'MD',
+                        'Massachusetts' => 'MA',
+                        'Michigan' => 'MI',
+                        'Minnesota' => 'MN',
+                        'Mississippi' => 'MS',
+                        'Missouri' => 'MO',
+                        'Montana' => 'MT',
+                        'Nebraska' => 'NE',
+                        'Nevada' => 'NV',
+                        'New Hampshire' => 'NH',
+                        'New Jersey' => 'NJ',
+                        'New Mexico' => 'NM',
+                        'New York' => 'NY',
+                        'North Carolina' => 'NC',
+                        'North Dakota' => 'ND',
+                        'Northern Mariana Islands' => 'MP',
+                        'Ohio' => 'OH',
+                        'Oklahoma' => 'OK',
+                        'Oregon' => 'OR',
+                        'Palau' => 'PW',
+                        'Pennsylvania' => 'PA',
+                        'Puerto Rico' => 'PR',
+                        'Rhode Island' => 'RI',
+                        'South Carolina' => 'SC',
+                        'South Dakota' => 'SD',
+                        'Tennessee' => 'TN',
+                        'Texas' => 'TX',
+                        'Utah' => 'UT',
+                        'Vermont' => 'VT',
+                        'Virgin Islands' => 'VI',
+                        'Virginia' => 'VA',
+                        'Washington' => 'WA',
+                        'West Virginia' => 'WV',
+                        'Wisconsin' => 'WI',
+                        'Wyoming' => 'WY',
+                        'Armed Forces Americas' => 'AA',
+                        'Armed Forces' => 'AE',
+                        'Armed Forces Pacific' => 'AP');
+
+        $this->AVSCodes = array("A" => "Address Matches Only (No ZIP)",
+                                  "B" => "Address Matches Only (No ZIP)",
+                                  "C" => "This tranaction was declined.",
+                                  "D" => "Address and Postal Code Match",
+                                  "E" => "This transaction was declined.",
+                                  "F" => "Address and Postal Code Match",
+                                  "G" => "Global Unavailable - N/A",
+                                  "I" => "International Unavailable - N/A",
+                                  "N" => "None - Transaction was declined.",
+                                  "P" => "Postal Code Match Only (No Address)",
+                                  "R" => "Retry - N/A",
+                                  "S" => "Service not supported - N/A",
+                                  "U" => "Unavailable - N/A",
+                                  "W" => "Nine-Digit ZIP Code Match (No Address)",
+                                  "X" => "Exact Match - Address and Nine-Digit ZIP",
+                                  "Y" => "Address and five-digit Zip match",
+                                  "Z" => "Five-Digit ZIP Matches (No Address)");
+
+        $this->CVV2Codes = array(
+                                    "E" => "N/A",
+                                    "M" => "Match",
+                                    "N" => "No Match",
+                                    "P" => "Not Processed - N/A",
+                                    "S" => "Service Not Supported - N/A",
+                                    "U" => "Service Unavailable - N/A",
+                                    "X" => "No Response - N/A"
+                                    );
+
+        $this->CurrencyCodes = array(
+                                        'AUD' => 'Austrailian Dollar',
+                                        'BRL' => 'Brazilian Real',
+                                        'CAD' => 'Canadian Dollar',
+                                        'CZK' => 'Czeck Koruna',
+                                        'DKK' => 'Danish Krone',
+                                        'EUR' => 'Euro',
+                                        'HKD' => 'Hong Kong Dollar',
+                                        'HUF' => 'Hungarian Forint',
+                                        'ILS' => 'Israeli New Sheqel',
+                                        'JPY' => 'Japanese Yen',
+                                        'MYR' => 'Malaysian Ringgit',
+                                        'MXN' => 'Mexican Peso',
+                                        'NOK' => 'Norwegian Krone',
+                                        'NZD' => 'New Zealand Dollar',
+                                        'PHP' => 'Philippine Peso',
+                                        'PLN' => 'Polish Zloty',
+                                        'GBP' => 'Pound Sterling',
+                                        'SGD' => 'Singapore Dollar',
+                                        'SEK' => 'Swedish Krona',
+                                        'CHF' => 'Swiss Franc',
+                                        'TWD' => 'Taiwan New Dollar',
+                                        'THB' => 'Thai Baht',
+                                        'USD' => 'U.S. Dollar'
+                                        );
+    }  // End function PayPalPro()
+
+    /**
+     * Get the current API version setting.
+     *
+     * @access  public
+     * @return  string  Returns the current value for API version.
+     */
+    function GetAPIVersion()
+    {
+        return $this->APIVersion;
+    }
+
+    /**
+     * Get the country code of the requested country.
+     *
+     * @access  public
+     * @param   string  $CountryName    Name of the country to return the code for.
+     * @return  string  Returns the country code for the supplied country name.
+     */
+    function GetCountryCode($CountryName)
+    {
+        return $this->Countries[$CountryName];
+    }
+
+    /**
+     * Get the state code for a requestad state.
+     *
+     * @access  public
+     * @param   string  $StateOrProvinceName    Name of the state or province to return the code for.
+     * @return  string  Returns the 2-letter code for the supplied state or province name.
+     */
+    function GetStateCode($StateOrProvinceName)
+    {
+        return $this->States[$StateOrProvinceName];
+    }
+
+    /**
+     * Get the country name based on the country code.
+     *
+     * @access  public
+     * @param   string  $CountryCode    Country code that you would like the full name for.
+     * @return  string  Returns the country name for the supplied country code.
+     */
+    function GetCountryName($CountryCode)
+    {
+        $Countries = array_flip($this->Countries);
+        return $Countries[$CountryCode];
+    }
+
+    /**
+     * Get the state name based on the 2-letter code.
+     *
+     * @access  public
+     * @param   mixed[] $StateOrProvinceName    State or province name that you would like the full name for.
+     * @return  string  Returns the full name of the state or province for the supplied code.
+     */
+    function GetStateName($StateOrProvinceName)
+    {
+        $States = array_flip($this->States);
+        return $States[$StateOrProvinceName];
+    }
+
+    /**
+     * Get the AVS (address verification) message.
+     *
+     * @access  public
+     * @param   string  $AVSCode    Address verification result code.
+     * @return  string  Returns the full message for the supplied AVS code.
+     */
+    function GetAVSCodeMessage($AVSCode)
+    {
+        return $this->AVSCodes[$AVSCode];
+    }
+
+    /**
+     * Get the security digits (CVV2 Code) message.
+     *
+     * @access  public
+     * @param   string  $CVV2Code   Credit card security digits.
+     * @return  string  Returns the full message for the supplied CVV2 code.
+     */
+    function GetCVV2CodeMessage($CVV2Code)
+    {
+        return $this->CVV2Codes[$CVV2Code];
+    }
+
+    /**
+     * Get the currency code text value.
+     *
+     * @access  public
+     * @param   string  $CurrencyCode   Currency code that you would like the full text for.
+     * @return  string  Returns the full name for the supplied currency code.
+     */
+    function GetCurrencyCodeText($CurrencyCode)
+    {
+        return $this->CurrencyCodes[$CurrencyCode];
+    }
+
+    /**
+     * Get the currency code based on the text value.
+     *
+     * @access  public
+     * @param   string  $CurrencyCodeText   Full name for a currency.
+     * @return  string  Returns the full name for the supplied currency code.
+     */
+    function GetCurrencyCode($CurrencyCodeText)
+    {
+        $CurrencyCodes = array_flip($this->CurrencyCodes);
+        return $CurrencyCodes[$CurrencyCodeText];
+    }
+
+    /**
+     * Send the API request to PayPal using CURL.
+     *
+     * @access  public
+     * @param   string  $Request        Raw API request string.
+     * @param   string  $APIName        The name of the API which you are calling.
+     * @param   string  $APIOperation   The method of the API which you are calling.
+     * @param   string  $PrintHeaders   The option to print headers or not.
+     * @return  string  $Response       Returns the raw HTTP response from PayPal.
+     */
+    function CURLRequest($Request = "", $APIName = "", $APIOperation = "", $PrintHeaders = false)
+    {
+        $curl = curl_init();
+        // curl_setopt($curl, CURLOPT_HEADER,TRUE);
+        curl_setopt($curl, CURLOPT_VERBOSE, $this->Sandbox);
+        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
+        curl_setopt($curl, CURLOPT_URL, $this->EndPointURL);
+        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+        curl_setopt($curl, CURLOPT_POSTFIELDS, $Request);
+
+        if ($this->APIMode == 'Certificate') {
+            curl_setopt($curl, CURLOPT_SSLCERT, $this->PathToCertKeyPEM);
+        }
+
+        $Response = curl_exec($curl);
+
+        /*
+         * If a cURL error occurs, output it for review.
+         */
+        if ($this->Sandbox) {
+            if (curl_error($curl)) {
+                echo curl_error($curl) . '

'; + } + } + + curl_close($curl); + $this->TPV_Parse_Request($Response, $Request, '24', $this->Sandbox, true); + return $Response; + } + + /** + * Convert an NVP string to an array with URL decoded values. + * + * @access public + * @param string $NVPString Name-value-pair string that you would like to convert to an array. + * @return mixed[] Returns the NVP string as an array structure. + */ + function NVPToArray($NVPString) + { + $proArray = array(); + while (strlen($NVPString)) { + // name + $keypos = strpos($NVPString, '='); + $keyval = substr($NVPString, 0, $keypos); + // value + $valuepos = strpos($NVPString, '&') ? strpos($NVPString, '&') : strlen($NVPString); + $valval = substr($NVPString, $keypos + 1, $valuepos - $keypos - 1); + // decoding the respose + $proArray[$keyval] = urldecode($valval); + $NVPString = substr($NVPString, $valuepos + 1, strlen($NVPString)); + } + + return $proArray; + } + + /** + * Check whether or not the API call was successful. + * + * @access public + * @param string $ack The value for ACK returned by a PayPal API response. + * @return boolean Returns a boolean (true/false) value for whether or not the ACK supplied is successful. + */ + function APICallSuccessful($ack) + { + if (strtoupper($ack) != 'SUCCESS' && strtoupper($ack) != 'SUCCESSWITHWARNING' && strtoupper($ack) != 'PARTIALSUCCESS') { + return false; + } else { + return true; + } + } + + /** + * Check whether or not warnings were returned. + * + * @access public + * @param string $ack The value for ACK returned by a PayPal API response. + * @return boolean Returns a boolean (true/false) value for whether or not the response includes warnings. + */ + function WarningsReturned($ack) + { + if (strpos(strtoupper($ack), 'WARNING') !== false) { + return true; + } else { + false; + } + } + + /** + * Get all errors returned from PayPal. + * + * @access public + * @param mixed[] $DataArray Array structure of PayPal NVP response. + * @return mixed[] $Errors Returns an array structure of all errors / warnings returned in a PayPal HTTP response. + */ + function GetErrors($DataArray) + { + + $Errors = array(); + $n = 0; + while (isset($DataArray['L_ERRORCODE' . $n . ''])) { + $LErrorCode = isset($DataArray['L_ERRORCODE' . $n . '']) ? $DataArray['L_ERRORCODE' . $n . ''] : ''; + $LShortMessage = isset($DataArray['L_SHORTMESSAGE' . $n . '']) ? $DataArray['L_SHORTMESSAGE' . $n . ''] : ''; + $LLongMessage = isset($DataArray['L_LONGMESSAGE' . $n . '']) ? $DataArray['L_LONGMESSAGE' . $n . ''] : ''; + $LSeverityCode = isset($DataArray['L_SEVERITYCODE' . $n . '']) ? $DataArray['L_SEVERITYCODE' . $n . ''] : ''; + + $CurrentItem = array( + 'L_ERRORCODE' => $LErrorCode, + 'L_SHORTMESSAGE' => $LShortMessage, + 'L_LONGMESSAGE' => $LLongMessage, + 'L_SEVERITYCODE' => $LSeverityCode + ); + + array_push($Errors, $CurrentItem); + $n++; + } + + return $Errors; + } + + /** + * Display errors on screen using line breaks. + * + * @access public + * @param mixed[] $Errors An array structure of errors returned in a PayPal HTTP response. + * @return output Returns an HTML string of the errors passed in for basic display purposes. + */ + function DisplayErrors($Errors) + { + foreach ($Errors as $ErrorVar => $ErrorVal) { + $CurrentError = $Errors[$ErrorVar]; + foreach ($CurrentError as $CurrentErrorVar => $CurrentErrorVal) { + if ($CurrentErrorVar == 'L_ERRORCODE') { + $CurrentVarName = 'Error Code'; + } elseif ($CurrentErrorVar == 'L_SHORTMESSAGE') { + $CurrentVarName = 'Short Message'; + } elseif ($CurrentErrorVar == 'L_LONGMESSAGE') { + $CurrentVarName = 'Long Message'; + } elseif ($CurrentErrorVar == 'L_SEVERITYCODE') { + $CurrentVarName = 'Severity Code'; + } + + echo $CurrentVarName . ': ' . $CurrentErrorVal . '
'; + } + echo '
'; + } + } + + /** + * Parse order items from an NVP string. + * + * @access public + * @param mixed[] $DataArray An array structure of a PayPal HTTP response. + * @return mixed[] Returns an array structure of the order items included in a PayPal HTTP response. + */ + function GetOrderItems($DataArray) + { + + $OrderItems = array(); + $n = 0; + while (isset($DataArray['L_NAME' . $n . ''])) { + $LName = isset($DataArray['L_NAME' . $n . '']) ? $DataArray['L_NAME' . $n . ''] : ''; + $LDesc = isset($DataArray['L_DESC' . $n . '']) ? $DataArray['L_DESC' . $n . ''] : ''; + $LNumber = isset($DataArray['L_NUMBER' . $n . '']) ? $DataArray['L_NUMBER' . $n . ''] : ''; + $LQTY = isset($DataArray['L_QTY' . $n . '']) ? $DataArray['L_QTY' . $n . ''] : ''; + $LAmt = isset($DataArray['L_AMT' . $n . '']) ? $DataArray['L_AMT' . $n . ''] : ''; + $LTaxAmt = isset($DataArray['L_TAXAMT' . $n . '']) ? $DataArray['L_TAXAMT' . $n . ''] : ''; + $LOptionsName = isset($DataArray['L_OPTIONSNAME' . $n . '']) ? $DataArray['L_OPTIONSNAME' . $n . ''] : ''; + $LOptionsValue = isset($DataArray['L_OPTIONSVALUE' . $n . '']) ? $DataArray['L_OPTIONSVALUE' . $n . ''] : ''; + $LItemWeightValue = isset($DataArray['L_ITEMWEIGHTVALUE' . $n . '']) ? $DataArray['L_ITEMWEIGHTVALUE' . $n . ''] : ''; + $LItemWeightUnit = isset($DataArray['L_ITEMWEIGHTUNIT' . $n . '']) ? $DataArray['L_ITEMWEIGHTUNIT' . $n . ''] : ''; + $LItemWidthValue = isset($DataArray['L_ITEMWEIGHTVALUE' . $n . '']) ? $DataArray['L_ITEMWEIGHTVALUE' . $n . ''] : ''; + $LItemWidthUnit = isset($DataArray['L_ITEMWIDTHUNIT' . $n . '']) ? $DataArray['L_ITEMWIDTHUNIT' . $n . ''] : ''; + $LItemLengthValue = isset($DataArray['L_ITEMLENGTHVALUE' . $n . '']) ? $DataArray['L_ITEMLENGTHVALUE' . $n . ''] : ''; + $LItemLengthUnit = isset($DataArray['L_ITEMLENGTHUNIT' . $n . '']) ? $DataArray['L_ITEMLENGTHUNIT' . $n . ''] : ''; + $LeBayTransID = isset($DataArray['L_EBAYITEMTXNID' . $n . '']) ? $DataArray['L_EBAYITEMTXNID' . $n . ''] : ''; + $LeBayOrderID = isset($DataArray['L_EBAYITEMORDERID' . $n . '']) ? $DataArray['L_EBAYITEMORDERID' . $n . ''] : ''; + + $CurrentItem = array( + 'L_NAME' => $LName, + 'L_DESC' => $LDesc, + 'L_NUMBER' => $LNumber, + 'L_QTY' => $LQTY, + 'L_AMT' => $LAmt, + 'L_OPTIONSNAME' => $LOptionsName, + 'L_OPTIONSVALUE' => $LOptionsValue, + 'L_ITEMWEIGHTVALUE' => $LItemWeightValue, + 'L_ITEMWEIGHTUNIT' => $LItemWeightUnit, + 'L_ITEMWIDTHVALUE' => $LItemWidthValue, + 'L_ITEMWIDTHUNIT' => $LItemWidthUnit, + 'L_ITEMLENGTHVALUE' => $LItemLengthValue, + 'L_ITEMLENGTHUNIT' => $LItemLengthUnit, + 'L_TAXAMT' => $LTaxAmt, + 'L_EBAYITEMTXNID' => $LeBayTransID, + 'L_EBAYITEMORDERID' => $LeBayOrderID + ); + + array_push($OrderItems, $CurrentItem); + $n++; + } + + return $OrderItems; + } // End function GetOrderItems + + + /** + * Get all payment(s) details from an NVP string. + * + * @access public + * @param mixed[] $DataArray Array structure from a PayPal HTTP response. + * @return mixed[] Returns an array structure for all of the payments included in a PayPal NVP response. + */ + function GetPayments($DataArray) + { + $Payments = array(); + $n = 0; + while (isset($DataArray['PAYMENTREQUEST_' . $n . '_AMT'])) { + $Payment = array( + 'SHIPTONAME' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTONAME']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTONAME'] : '', + 'SHIPTOSTREET' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET'] : '', + 'SHIPTOSTREET2' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET2']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTREET2'] : '', + 'SHIPTOCITY' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCITY']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCITY'] : '', + 'SHIPTOSTATE' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTATE']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOSTATE'] : '', + 'SHIPTOZIP' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOZIP']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOZIP'] : '', + 'SHIPTOCOUNTRYCODE' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYCODE']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYCODE'] : '', + 'SHIPTOCOUNTRYNAME' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYNAME']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOCOUNTRYNAME'] : '', + 'SHIPTOPHONENUM' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOPHONENUM']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPTOPHONENUM'] : '', + 'ADDRESSSTATUS' => isset($DataArray['PAYMENTREQUEST_' . $n . '_ADDRESSSTATUS']) ? $DataArray['PAYMENTREQUEST_' . $n . '_ADDRESSSTATUS'] : '', + 'AMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_AMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_AMT'] : '', + 'CURRENCYCODE' => isset($DataArray['PAYMENTREQUEST_' . $n . '_CURRENCYCODE']) ? $DataArray['PAYMENTREQUEST_' . $n . '_CURRENCYCODE'] : '', + 'ITEMAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_ITEMAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_ITEMAMT'] : '', + 'SHIPPINGAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_SHIPPINGAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_SHIPPINGAMT'] : '', + 'INSURANCEOPTIONOFFERED' => isset($DataArray['PAYMENTREQUEST_' . $n . '_INSURANCEOPTIONOFFERED']) ? $DataArray['PAYMENTREQUEST_' . $n . '_INSURANCEOPTIONOFFERED'] : '', + 'HANDLINGAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_HANDLINGAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_HANDLINGAMT'] : '', + 'TAXAMT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_TAXAMT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_TAXAMT'] : '', + 'DESC' => isset($DataArray['PAYMENTREQUEST_' . $n . '_DESC']) ? $DataArray['PAYMENTREQUEST_' . $n . '_DESC'] : '', + 'CUSTOM' => isset($DataArray['PAYMENTREQUEST_' . $n . '_CUSTOM']) ? $DataArray['PAYMENTREQUEST_' . $n . '_CUSTOM'] : '', + 'INVNUM' => isset($DataArray['PAYMENTREQUEST_' . $n . '_INVNUM']) ? $DataArray['PAYMENTREQUEST_' . $n . '_INVNUM'] : '', + 'NOTIFYURL' => isset($DataArray['PAYMENTREQUEST_' . $n . '_NOTIFYURL']) ? $DataArray['PAYMENTREQUEST_' . $n . '_NOTIFYURL'] : '', + 'NOTETEXT' => isset($DataArray['PAYMENTREQUEST_' . $n . '_NOTETEXT']) ? $DataArray['PAYMENTREQUEST_' . $n . '_NOTETEXT'] : '', + 'TRANSACTIONID' => isset($DataArray['PAYMENTREQUEST_' . $n . '_TRANSACTIONID']) ? $DataArray['PAYMENTREQUEST_' . $n . '_TRANSACTIONID'] : '', + 'ALLOWEDPAYMENTMETHOD' => isset($DataArray['PAYMENTREQUEST_' . $n . '_ALLOWEDPAYMENTMETHOD']) ? $DataArray['PAYMENTREQUEST_' . $n . '_ALLOWEDPAYMENTMETHOD'] : '', + 'PAYMENTREQUESTID' => isset($DataArray['PAYMENTREQUEST_' . $n . '_PAYMENTREQUESTID']) ? $DataArray['PAYMENTREQUEST_' . $n . '_PAYMENTREQUESTID'] : '' + ); + + $n_items = 0; + $OrderItems = array(); + while (isset($DataArray['L_PAYMENTREQUEST_' . $n . '_AMT' . $n_items])) { + $Item = array( + 'NAME' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_NAME' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_NAME' . $n_items] : '', + 'DESC' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_DESC' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_DESC' . $n_items] : '', + 'AMT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_AMT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_AMT' . $n_items] : '', + 'NUMBER' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_NUMBER' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_NUMBER' . $n_items] : '', + 'QTY' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_QTY' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_QTY' . $n_items] : '', + 'TAXAMT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_TAXAMT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_TAXAMT' . $n_items] : '', + 'ITEMWEIGHTVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTVALUE' . $n_items] : '', + 'ITEMWEIGHTUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWEIGHTUNIT' . $n_items] : '', + 'ITEMLENGTHVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHVALUE' . $n_items] : '', + 'ITEMLENGTHUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMLENGTHUNIT' . $n_items] : '', + 'ITEMWIDTHVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHVALUE' . $n_items] : '', + 'ITEMWIDTHUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMWIDTHUNIT' . $n_items] : '', + 'ITEMHEIGHTVALUE' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTVALUE' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTVALUE' . $n_items] : '', + 'ITEMHEIGHTUNIT' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTUNIT' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_ITEMHEIGHTUNIT' . $n_items] : '', + 'EBAYITEMNUMBER' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMNUMBER' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMNUMBER' . $n_items] : '', + 'EBAYAUCTIONTXNID' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYAUCTIONTXNID' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYAUCTIONTXNID' . $n_items] : '', + 'EBAYITEMORDERID' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMORDERID' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMORDERID' . $n_items] : '', + 'EBAYITEMCARTID' => isset($DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMCARTID' . $n_items]) ? $DataArray['L_PAYMENTREQUEST_' . $n . '_EBAYITEMCARTID' . $n_items] : '' + ); + + array_push($OrderItems, $Item); + $n_items++; + } + $Payment['ORDERITEMS'] = $OrderItems; + + array_push($Payments, $Payment); + $n++; + } + + return $Payments; + } + + /** + * Parse payment info from Express Checkout API response. + * + * @access public + * @param mixed[] $DataArray Array structure of a PayPal HTTP response. + * @return mixed[] Returns an array structure of the payment details for each payment on a PayPal HTTP response. + */ + function GetExpressCheckoutPaymentInfo($DataArray) + { + $Payments = array(); + $n = 0; + + while (isset($DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONID'])) { + $PaymentInfo = array( + 'TRANSACTIONID' => isset($DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONID']) ? $DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONID'] : '', + 'TRANSACTIONTYPE' => isset($DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE']) ? $DataArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE'] : '', + 'PAYMENTTYPE' => isset($DataArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE']) ? $DataArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE'] : '', + 'ORDERTIME' => isset($DataArray['PAYMENTINFO_' . $n . '_ORDERTIME']) ? $DataArray['PAYMENTINFO_' . $n . '_ORDERTIME'] : '', + 'AMT' => isset($DataArray['PAYMENTINFO_' . $n . '_AMT']) ? $DataArray['PAYMENTINFO_' . $n . '_AMT'] : '', + 'CURRENCYCODE' => isset($DataArray['PAYMENTINFO_' . $n . '_CURRENCYCODE']) ? $DataArray['PAYMENTINFO_' . $n . '_CURRENCYCODE'] : '', + 'FEEAMT' => isset($DataArray['PAYMENTINFO_' . $n . '_FEEAMT']) ? $DataArray['PAYMENTINFO_' . $n . '_FEEAMT'] : '', + 'SETTLEAMT' => isset($DataArray['PAYMENTINFO_' . $n . '_SETTLEAMT']) ? $DataArray['PAYMENTINFO_' . $n . '_SETTLEAMT'] : '', + 'TAXAMT' => isset($DataArray['PAYMENTINFO_' . $n . '_TAXAMT']) ? $DataArray['PAYMENTINFO_' . $n . '_TAXAMT'] : '', + 'EXCHANGERATE' => isset($DataArray['PAYMENTINFO_' . $n . '_EXCHANGERATE']) ? $DataArray['PAYMENTINFO_' . $n . '_EXCHANGERATE'] : '', + 'PAYMENTSTATUS' => isset($DataArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS']) ? $DataArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS'] : '', + 'PENDINGREASON' => isset($DataArray['PAYMENTINFO_' . $n . '_PENDINGREASON']) ? $DataArray['PAYMENTINFO_' . $n . '_PENDINGREASON'] : '', + 'REASONCODE' => isset($DataArray['PAYMENTINFO_' . $n . '_REASONCODE']) ? $DataArray['PAYMENTINFO_' . $n . '_REASONCODE'] : '', + 'PROTECTIONELIGIBILITY' => isset($DataArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY']) ? $DataArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY'] : '', + 'EBAYITEMAUCTIONTRANSACTIONID' => isset($DataArray['PAYMENTINFO_' . $n . '_EBAYITEMAUCTIONTRANSACTIONID']) ? $DataArray['PAYMENTINFO_' . $n . '_EBAYITEMAUCTIONTRANSACTIONID'] : '', + 'PAYMENTREQUESTID' => isset($DataArray['PAYMENTINFO_' . $n . '_PAYMENTREQUESTID']) ? $DataArray['PAYMENTINFO_' . $n . '_PAYMENTREQUESTID'] : '' + ); + + array_push($Payments, $PaymentInfo); + $n++; + } + return $Payments; + } + + /** + * Mask the API credential values in the API call for logging purposes. + * + * @access public + * @param string $api_result Raw NVP string. + * @return string Returns the raw NVP string with the API credentials masked. + */ + function MaskAPIResult($api_result) + { + $api_result_array = $this->NVPToArray($api_result); + $api_result = ''; + if (isset($api_result_array['SIGNATURE'])) { + $api_result_array['USER'] = '*****'; + $api_result_array['PWD'] = '*****'; + $api_result_array['SIGNATURE'] = '*****'; + } + if (isset($api_result_array['ACCT'])) { + $api_result_array['ACCT'] = '*****' . substr($api_result_array['ACCT'], -4); + } + if (isset($api_result_array['CVV2'])) { + $api_result_array['CVV2'] = '*****'; + } + $api_result = urldecode(http_build_query($api_result_array)); + return $api_result; + } + + /** + * Save log info to a location on the disk. + * + * @param $log_path + * @param $filename + * @param $string_data + * @return bool + */ + function Logger($log_path, $filename, $string_data) + { + + if ($this->LogResults) { + $timestamp = strtotime('now'); + $timestamp = date('mdY_gi_s_A_', $timestamp); + $string_data_array = $this->NVPToArray($string_data); + $file = $log_path . $timestamp . $filename . '.txt'; + $fh = fopen($file, 'w'); + fwrite($fh, $string_data . chr(13) . chr(13) . print_r($string_data_array, true)); + fclose($fh); + } + + return true; + } + + /** + * Captures an authorized payment. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoCapture($DataArray) + { + $DCFieldsNVP = '&METHOD=DoCapture'; + + // DoCapture Fields + $DCFields = isset($DataArray['DCFields']) ? $DataArray['DCFields'] : array(); + + foreach ($DCFields as $DCFieldsVar => $DCFieldsVal) { + $DCFieldsNVP .= $DCFieldsVal != '' ? '&' . strtoupper($DCFieldsVar) . '=' . urlencode($DCFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DCFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Authorize a payment. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoAuthorization($DataArray) + { + $DAFieldsNVP = '&METHOD=DoAuthorization'; + + $DAFields = isset($DataArray['DAFields']) ? $DataArray['DAFields'] : array(); + + foreach ($DAFields as $DAFieldsVar => $DAFieldsVal) { + $DAFieldsNVP .= $DAFieldsVal != '' ? '&' . strtoupper($DAFieldsVar) . '=' . urlencode($DAFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DAFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Reauthorize an existing authorization transaction. + * + * The resulting reauthorization is a new transaction with a new AUTHORIZATIONID. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoReauthorization($DataArray) + { + $DRFieldsNVP = '&METHOD=DoReAuthorization'; + + $DRFields = isset($DataArray['DRFields']) ? $DataArray['DRFields'] : array(); + + foreach ($DRFields as $DRFieldsVar => $DRFieldsVal) { + $DRFieldsNVP .= $DRFieldsVal != '' ? '&' . strtoupper($DRFieldsVar) . '=' . urlencode($DRFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DRFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Change the shipping address of an existing authorization transaction. + * + * In order to use this API operation, the original authorization should + * still be open, not completed, not reversed, not voided, and not on hold + * for any reason. + * + * Advanced permission from PayPal is required to use this API operation. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function UpdateAuthorization($DataArray) + { + $UAFieldsNVP = '&METHOD=UpdateAuthorization'; + + $UAFields = isset($DataArray['UAFields']) ? $DataArray['UAFields'] : array(); + + foreach ($UAFields as $UAFieldsVar => $UAFieldsVal) { + $UAFieldsNVP .= $UAFieldsVal != '' ? '&' . strtoupper($UAFieldsVar) . '=' . urlencode($UAFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $UAFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Void an order or an authorization. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoVoid($DataArray) + { + $DVFieldsNVP = '&METHOD=DoVoid'; + + $DVFields = isset($DataArray['DVFields']) ? $DataArray['DVFields'] : array(); + + foreach ($DVFields as $DVFieldsVar => $DVFieldsVal) { + $DVFieldsNVP .= $DVFieldsVal != '' ? '&' . strtoupper($DVFieldsVar) . '=' . urlencode($DVFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DVFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Make a payment to one or more PayPal account holders. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function MassPay($DataArray) + { + $MPFieldsNVP = '&METHOD=MassPay'; + $MPItemsNVP = ''; + + // MassPay Fields + $MPFields = isset($DataArray['MPFields']) ? $DataArray['MPFields'] : array(); + + foreach ($MPFields as $MPFieldsVar => $MPFieldsVal) { + $MPFieldsNVP .= $MPFieldsVal != '' ? '&' . strtoupper($MPFieldsVar) . '=' . urlencode($MPFieldsVal) : ''; + } + + // MassPay Items Fields + $MPItems = isset($DataArray['MPItems']) ? $DataArray['MPItems'] : array(); + $n = 0; + foreach ($MPItems as $MPItemsVar => $MPItemsVal) { + $CurrentItem = $MPItems[$MPItemsVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $MPItemsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; + } + $n++; + } + + $NVPRequest = $this->NVPCredentials . $MPFieldsNVP . $MPItemsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Issue a refund to the PayPal account holder associated with a transaction. + * + * This API operation can be used to issue a full or partial refund for any transaction + * within a default period of 60 days from when the payment is received. + * + * After the refund period has passed, merchants can no longer use the RefundTransaction + * API operation to issue refunds. Instead, merchants can manually issue a credit to the + * buyer by logging into their PayPal account; for PayPal payments, a credit can be issued + * by clicking Send Money. Alternatively, merchants can use the MassPay API to credit + * PayPal accounts or utilize the DoNonReferencedCredit API operation to issue a credit to + * a card without referencing the original transaction. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function RefundTransaction($DataArray) + { + $RTFieldsNVP = '&METHOD=RefundTransaction'; + + $RTFields = isset($DataArray['RTFields']) ? $DataArray['RTFields'] : array(); + $MerchantDataVars = isset($DataArray['MerchantDataVars']) ? $DataArray['MerchantDataVars'] : array(); + + foreach ($RTFields as $RTFieldsVar => $RTFieldsVal) { + $RTFieldsNVP .= $RTFieldsVal != '' ? '&' . strtoupper($RTFieldsVar) . '=' . urlencode($RTFieldsVal) : ''; + } + + $n = 0; + foreach ($MerchantDataVars as $MerchantData) { + $MerchantDataKey = $MerchantData['key']; + $MerchantDataValue = $MerchantData['value']; + $RTFieldsNVP .= $MerchantData['value'] != '' ? '&MERCHANTDATA' . $n . 'KEY=' . urlencode($MerchantData['key']) . + '&MERCHANTDATA' . $n . 'VALUE=' . urlencode($MerchantData['value']) : ''; + $n++; + } + + $NVPRequest = $this->NVPCredentials . $RTFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Obtain information about a specific transaction. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetTransactionDetails($DataArray) + { + $GTDFieldsNVP = '&METHOD=GetTransactionDetails'; + + $GTDFields = isset($DataArray['GTDFields']) ? $DataArray['GTDFields'] : array(); + + foreach ($GTDFields as $GTDFieldsVar => $GTDFieldsVal) { + $GTDFieldsNVP .= $GTDFieldsVal != '' ? '&' . strtoupper($GTDFieldsVar) . '=' . urlencode($GTDFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $GTDFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $OrderItems = $this->GetOrderItems($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['ORDERITEMS'] = $OrderItems; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Process a credit card payment. + * + * This is only available with Website Payments Pro 3.0. + * If you're on Payments Pro 2.0 you'll need to use PayFlow instead. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoDirectPayment($DataArray) + { + // Create empty holders for each portion of the NVP string + $DPFieldsNVP = '&METHOD=DoDirectPayment'; + $CCDetailsNVP = ''; + $PayerInfoNVP = ''; + $PayerNameNVP = ''; + $BillingAddressNVP = ''; + $ShippingAddressNVP = ''; + $PaymentDetailsNVP = ''; + $OrderItemsNVP = ''; + $Secure3DNVP = ''; + + // DP Fields + $DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array(); + foreach ($DPFields as $DPFieldsVar => $DPFieldsVal) { + $DPFieldsNVP .= $DPFieldsVal != '' ? '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal) : ''; + } + + // CC Details Fields + $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); + foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) { + $CCDetailsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; + } + + // PayerInfo Type Fields + $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); + foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) { + $PayerInfoNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; + } + + // Payer Name Fields + $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); + foreach ($PayerName as $PayerNameVar => $PayerNameVal) { + $PayerNameNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; + } + + // Address Fields (Billing) + $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); + foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) { + $BillingAddressNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; + } + + // Payment Details Type Fields + $PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array(); + foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) { + $PaymentDetailsNVP .= $PaymentDetailsVal != '' ? '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal) : ''; + } + + // Payment Details Item Type Fields + $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array(); + $n = 0; + foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) { + $CurrentItem = $OrderItems[$OrderItemsVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $OrderItemsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; + } + $n++; + } + + // Ship To Address Fields + $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); + foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) { + $ShippingAddressNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; + } + + // 3D Secure Fields + $Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array(); + foreach ($Secure3D as $Secure3DVar => $Secure3DVal) { + $Secure3DNVP .= $Secure3DVal != '' ? '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal) : ''; + } + + // Now that we have each chunk we need to go ahead and append them all together for our entire NVP string + $NVPRequest = $this->NVPCredentials . $DPFieldsNVP . $CCDetailsNVP . $PayerInfoNVP . $PayerNameNVP . $BillingAddressNVP . $PaymentDetailsNVP . $OrderItemsNVP . $ShippingAddressNVP . $Secure3DNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Initiate an Express Checkout transaction. + * + * Used to generate a unique TOKEN for use with the checkout. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function SetExpressCheckout($DataArray) + { + $SECFieldsNVP = '&METHOD=SetExpressCheckout'; + $SurveyChoicesNVP = ''; + $PaymentsNVP = ''; + $ShippingOptionsNVP = ''; + $BillingAgreementsNVP = ''; + + // SetExpressCheckout Request Fields + $SECFields = isset($DataArray['SECFields']) ? $DataArray['SECFields'] : array(); + foreach ($SECFields as $SECFieldsVar => $SECFieldsVal) { + if (strtoupper($SECFieldsVar) != 'SKIPDETAILS') { + $SECFieldsNVP .= $SECFieldsVal != '' ? '&' . strtoupper($SECFieldsVar) . '=' . urlencode($SECFieldsVal) : ''; + } else { + $SkipDetails = $SECFieldsVal ? true : false; + } + } + + // Check to see if the REDIRECTURL should include user-action + if (isset($SkipDetails) && $SkipDetails) { + $SkipDetailsOption = 'useraction=commit'; + } else { + $SkipDetailsOption = 'useraction=continue'; + } + + // Survey Choices + $SurveyChoices = isset($DataArray['SurveyChoices']) ? $DataArray['SurveyChoices'] : array(); + if (isset($SECFields['surveyquestion']) && $SECFields['surveyquestion'] != '') { + $n = 0; + foreach ($SurveyChoices as $SurveyChoice) { + $SurveyChoicesNVP .= $SurveyChoice != '' ? '&' . 'L_SURVEYCHOICE' . $n . '=' . urlencode($SurveyChoice) : ''; + $n++; + } + } + + // Payment Details Type Fields + $Payments = isset($DataArray['Payments']) ? $DataArray['Payments'] : array(); + $n = 0; + foreach ($Payments as $PaymentsVar => $PaymentsVal) { + $CurrentPayment = $Payments[$PaymentsVar]; + foreach ($CurrentPayment as $CurrentPaymentVar => $CurrentPaymentVal) { + if (strtoupper($CurrentPaymentVar) != 'ORDER_ITEMS') { + $PaymentsNVP .= $CurrentPaymentVal != '' ? '&PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentPaymentVar) . '=' . urlencode($CurrentPaymentVal) : ''; + } else { + $PaymentOrderItems = $CurrentPayment['order_items']; + $n_item = 0; + foreach ($PaymentOrderItems as $OrderItemsVar => $OrderItemsVal) { + $CurrentItem = $PaymentOrderItems[$OrderItemsVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $PaymentsNVP .= $CurrentItemVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentItemVar) . $n_item . '=' . urlencode($CurrentItemVal) : ''; + } + $n_item++; + } + } + } + $n++; + } + + // Billing Agreements + $BillingAgreements = isset($DataArray['BillingAgreements']) ? $DataArray['BillingAgreements'] : array(); + $n = 0; + foreach ($BillingAgreements as $BillingAgreementVar => $BillingAgreementVal) { + $CurrentItem = $BillingAgreements[$BillingAgreementVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $BillingAgreementsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; + } + $n++; + } + + // Shipping Options Fields + $ShippingOptions = isset($DataArray['ShippingOptions']) ? $DataArray['ShippingOptions'] : array(); + $n = 0; + foreach ($ShippingOptions as $ShippingOptionsVar => $ShippingOptionsVal) { + $CurrentOption = $ShippingOptions[$ShippingOptionsVar]; + foreach ($CurrentOption as $CurrentOptionVar => $CurrentOptionVal) { + $ShippingOptionsNVP .= $CurrentOptionVal != '' ? '&' . strtoupper($CurrentOptionVar) . $n . '=' . urlencode($CurrentOptionVal) : ''; + } + $n++; + } + + $NVPRequest = $this->NVPCredentials . $SECFieldsNVP . $SurveyChoicesNVP . $ShippingOptionsNVP . $BillingAgreementsNVP . $PaymentsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + if (isset($NVPResponseArray['TOKEN']) && $NVPResponseArray['TOKEN'] != '') { + if ($this->Sandbox) { + $NVPResponseArray['REDIRECTURLDIGITALGOODS'] = 'https://www.sandbox.paypal.com/incontext?' . $SkipDetailsOption . '&token=' . $NVPResponseArray['TOKEN']; + $NVPResponseArray['REDIRECTURL'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&' . $SkipDetailsOption . '&token=' . $NVPResponseArray['TOKEN']; + } else { + $NVPResponseArray['REDIRECTURLDIGITALGOODS'] = 'https://www.paypal.com/incontext?' . $SkipDetailsOption . '&token=' . $NVPResponseArray['TOKEN']; + $NVPResponseArray['REDIRECTURL'] = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&' . $SkipDetailsOption . '&token=' . $NVPResponseArray['TOKEN']; + } + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } // End function SetExpressCheckout() + + /** + * Generate an NVP response to return to PayPal's Instant Update (callback) API. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function CallbackResponse($DataArray) + { + $CBFieldsNVP = 'METHOD=CallbackResponse'; + $ShippingOptionsNVP = ''; + + // Basic callback response fields. + $CBFields = isset($DataArray['CBFields']) ? $DataArray['CBFields'] : array(); + foreach ($CBFields as $CBFieldsVar => $CBFieldsVal) { + $CBFieldsNVP .= $CBFieldsVal != '' ? '&' . strtoupper($CBFieldsVar) . '=' . urlencode($CBFieldsVal) : ''; + } + + // Shipping Options Fields + $ShippingOptions = isset($DataArray['ShippingOptions']) ? $DataArray['ShippingOptions'] : array(); + $n = 0; + foreach ($ShippingOptions as $ShippingOptionsVar => $ShippingOptionsVal) { + $CurrentOption = $ShippingOptions[$ShippingOptionsVar]; + foreach ($CurrentOption as $CurrentOptionVar => $CurrentOptionVal) { + $ShippingOptionsNVP .= $CurrentOptionVal != '' ? '&' . strtoupper($CurrentOptionVar) . $n . '=' . urlencode($CurrentOptionVal) : ''; + } + $n++; + } + + $NVPResponse = $CBFieldsNVP . $ShippingOptionsNVP; + $this->Logger($this->LogPath, __FUNCTION__, $NVPResponse); + + return $NVPResponse; + } + + /** + * Obtain details about an Express Checkout transaction. + * + * This is used after PayPal redirects the buyer back to your + * ReturnURL supplied in the SetExpressCheckout request. Data + * returned includes the buyer's name, shipping address, phone number, + * and general transaction details. + * + * @access public + * @param string $Token The token returned from a previous SetExpressCheckout request. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetExpressCheckoutDetails($Token) + { + $GECDFieldsNVP = '&METHOD=GetExpressCheckoutDetails&TOKEN=' . $Token; + + $NVPRequest = $this->NVPCredentials . $GECDFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $OrderItems = $this->GetOrderItems($NVPResponseArray); + $Payments = $this->GetPayments($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['ORDERITEMS'] = $OrderItems; + $NVPResponseArray['PAYMENTS'] = $Payments; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } // End function GetExpressCheckoutDetails() + + /** + * Complete an Express Checkout transaction. + * + * If you set up a billing agreement in your SetExpressCheckout API call, + * the billing agreement is created when you call the DoExpressCheckoutPayment + * API operation. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoExpressCheckoutPayment($DataArray) + { + $DECPFieldsNVP = '&METHOD=DoExpressCheckoutPayment'; + $PaymentsNVP = ''; + $UserSelectedOptionsNVP = ''; + + // DoExpressCheckoutPayment Fields + $DECPFields = isset($DataArray['DECPFields']) ? $DataArray['DECPFields'] : array(); + foreach ($DECPFields as $DECPFieldsVar => $DECPFieldsVal) { + $DECPFieldsNVP .= $DECPFieldsVal != '' ? '&' . strtoupper($DECPFieldsVar) . '=' . urlencode($DECPFieldsVal) : ''; + } + + // Payment Details Type Fields + $Payments = isset($DataArray['Payments']) ? $DataArray['Payments'] : array(); + $n = 0; + foreach ($Payments as $PaymentsVar => $PaymentsVal) { + $CurrentPayment = $Payments[$PaymentsVar]; + foreach ($CurrentPayment as $CurrentPaymentVar => $CurrentPaymentVal) { + if (strtoupper($CurrentPaymentVar) == 'ORDER_ITEMS') { + $PaymentOrderItems = $CurrentPayment['order_items']; + $n_item = 0; + foreach ($PaymentOrderItems as $OrderItemsVar => $OrderItemsVal) { + $CurrentItem = $PaymentOrderItems[$OrderItemsVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $PaymentsNVP .= $CurrentItemVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentItemVar) . $n_item . '=' . urlencode($CurrentItemVal) : ''; + } + $n_item++; + } + } elseif (strtoupper($CurrentPaymentVar) == 'REDEEMED_OFFERS') { + $RedeemedOffers = $CurrentPayment['redeemed_offers']; + $n_item = 0; + foreach ($RedeemedOffers as $RedeemedOfferVar => $RedeemedOfferVal) { + $CurrentRedeemedOffer = $RedeemedOffers[$RedeemedOfferVar]; + foreach ($CurrentRedeemedOffer as $CurrentRedeemedOfferVar => $CurrentRedeemedOfferVal) { + $PaymentsNVP .= $CurrentRedeemedOfferVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentRedeemedOfferVar) . $n_item . '=' . urlencode($CurrentRedeemedOfferVal) : ''; + } + $n_item++; + } + } elseif (strtoupper($CurrentPaymentVar) == 'MERCHANT_DATA_VARS') { + $MerchantDataVars = $CurrentPayment['merchant_data_vars']; + $n_item = 0; + foreach ($MerchantDataVars as $MerchantDataVarsVar => $MerchantDataVarsVal) { + $CurrentMerchantDataVar = $MerchantDataVars[$MerchantDataVarsVar]; + foreach ($CurrentMerchantDataVar as $CurrentMerchantDataVarVar => $CurrentMerchantDataVarVal) { + $PaymentsNVP .= $CurrentMerchantDataVarVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentMerchantDataVarVar) . $n_item . '=' . urlencode($CurrentMerchantDataVarVal) : ''; + } + $n_item++; + } + } else { + $PaymentsNVP .= $CurrentPaymentVal != '' ? '&PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentPaymentVar) . '=' . urlencode($CurrentPaymentVal) : ''; + } + } + $n++; + } + + // User Selected Options + $UserSelectedOptions = isset($DataArray['UserSelectedOptions']) ? $DataArray['UserSelectedOptions'] : array(); + foreach ($UserSelectedOptions as $UserSelectedOptionVar => $UserSelectedOptionVal) { + $UserSelectedOptionsNVP .= $UserSelectedOptionVal != '' ? '&' . strtoupper($UserSelectedOptionVar) . '=' . urlencode($UserSelectedOptionVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DECPFieldsNVP . $PaymentsNVP . $UserSelectedOptionsNVP; + $this->MaskAPIResult($NVPRequest); + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + // Loop through all possible payments and parse out data accordingly. + // This is to handle parallel payments. + $n = 0; + $Payments = array(); + while (isset($NVPResponseArray['PAYMENTINFO_' . $n . '_AMT'])) { + $Payment = array( + 'TRANSACTIONID' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONID']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONID'] : '', + 'TRANSACTIONTYPE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_TRANSACTIONTYPE'] : '', + 'PAYMENTTYPE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTTYPE'] : '', + 'ORDERTIME' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_ORDERTIME']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_ORDERTIME'] : '', + 'AMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_AMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_AMT'] : '', + 'FEEAMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_FEEAMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_FEEAMT'] : '', + 'SETTLEAMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_SETTLEAMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_SETTLEAMT'] : '', + 'TAXAMT' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_TAXAMT']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_TAXAMT'] : '', + 'EXCHANGERATE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_EXCHANGERATE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_EXCHANGERATE'] : '', + 'CURRENCYCODE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_CURRENCYCODE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_CURRENCYCODE'] : '', + 'PAYMENTSTATUS' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PAYMENTSTATUS'] : '', + 'PENDINGREASON' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PENDINGREASON']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PENDINGREASON'] : '', + 'REASONCODE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_REASONCODE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_REASONCODE'] : '', + 'PROTECTIONELIGIBILITY' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_PROTECTIONELIGIBILITY'] : '', + 'ERRORCODE' => isset($NVPResponseArray['PAYMENTINFO_' . $n . '_ERRORCODE']) ? $NVPResponseArray['PAYMENTINFO_' . $n . '_ERRORCODE'] : '' + ); + + // Pull out FMF info for current payment. + $FMFilters = array(); + $n_filters = 0; + while (isset($NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERID' . $n_filters])) { + $FMFilter = array( + 'ID' => isset($NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERID' . $n_filters]) ? $NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERID' . $n_filters] : '', + 'NAME' => isset($NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERNAME' . $n_filters]) ? $NVPResponseArray['L_PAYMENTINFO_' . $n . '_FMFFILTERNAME' . $n_filters] : '' + ); + $n_filters++; + } + $Payment['FMFILTERS'] = $FMFilters; + + // Pull error info for current payment. + $PaymentErrors = array(); + while (isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_ERRORCODE'])) { + $Error = array( + 'ERRORCODE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_ERRORCODE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_ERRORCODE'] : '', + 'SHORTMESSAGE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_SHORTMESSAGE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_SHORTMESSAGE'] : '', + 'LONGMESSAGE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_LONGMESSAGE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_LONGMESSAGE'] : '', + 'SEVERITYCODE' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_SEVERITYCODE']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_SEVERITYCODE'] : '', + 'ACK' => isset($NVPResponseArray['PAYMENTREQUEST_' . $n . '_ACK']) ? $NVPResponseArray['PAYMENTREQUEST_' . $n . '_ACK'] : '' + ); + array_push($PaymentErrors, $Error); + } + $Payment['ERRORS'] = $PaymentErrors; + + array_push($Payments, $Payment); + $n++; + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['PAYMENTS'] = $Payments; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Search PayPal transaction history for transactions that meet the specified criteria. + * + * The maximum number of transactions that can be returned from a TransactionSearch API call is 100. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function TransactionSearch($DataArray) + { + $TSFieldsNVP = '&METHOD=TransactionSearch'; + $PayerNameNVP = ''; + + // Transaction Search Fields + $TSFields = isset($DataArray['TSFields']) ? $DataArray['TSFields'] : array(); + foreach ($TSFields as $TSFieldsVar => $TSFieldsVal) { + $TSFieldsNVP .= $TSFieldsVal != '' ? '&' . strtoupper($TSFieldsVar) . '=' . urlencode($TSFieldsVal) : ''; + } + + // Payer Name Fields + $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); + foreach ($PayerName as $PayerNameVar => $PayerNameVal) { + $PayerNameNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $TSFieldsNVP . $PayerNameNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $SearchResults = array(); + $n = 0; + while (isset($NVPResponseArray['L_TIMESTAMP' . $n . ''])) { + $LTimestamp = isset($NVPResponseArray['L_TIMESTAMP' . $n . '']) ? $NVPResponseArray['L_TIMESTAMP' . $n . ''] : ''; + $LTimeZone = isset($NVPResponseArray['L_TIMEZONE' . $n . '']) ? $NVPResponseArray['L_TIMEZONE' . $n . ''] : ''; + $LType = isset($NVPResponseArray['L_TYPE' . $n . '']) ? $NVPResponseArray['L_TYPE' . $n . ''] : ''; + $LEmail = isset($NVPResponseArray['L_EMAIL' . $n . '']) ? $NVPResponseArray['L_EMAIL' . $n . ''] : ''; + $LName = isset($NVPResponseArray['L_NAME' . $n . '']) ? $NVPResponseArray['L_NAME' . $n . ''] : ''; + $LTransID = isset($NVPResponseArray['L_TRANSACTIONID' . $n . '']) ? $NVPResponseArray['L_TRANSACTIONID' . $n . ''] : ''; + $LStatus = isset($NVPResponseArray['L_STATUS' . $n . '']) ? $NVPResponseArray['L_STATUS' . $n . ''] : ''; + $LAmt = isset($NVPResponseArray['L_AMT' . $n . '']) ? $NVPResponseArray['L_AMT' . $n . ''] : ''; + $LFeeAmt = isset($NVPResponseArray['L_FEEAMT' . $n . '']) ? $NVPResponseArray['L_FEEAMT' . $n . ''] : ''; + $LNetAmt = isset($NVPResponseArray['L_NETAMT' . $n . '']) ? $NVPResponseArray['L_NETAMT' . $n . ''] : ''; + + $CurrentItem = array( + 'L_TIMESTAMP' => $LTimestamp, + 'L_TIMEZONE' => $LTimeZone, + 'L_TYPE' => $LType, + 'L_EMAIL' => $LEmail, + 'L_NAME' => $LName, + 'L_TRANSACTIONID' => $LTransID, + 'L_STATUS' => $LStatus, + 'L_AMT' => $LAmt, + 'L_FEEAMT' => $LFeeAmt, + 'L_NETAMT' => $LNetAmt + ); + + array_push($SearchResults, $CurrentItem); + $n++; + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['SEARCHRESULTS'] = $SearchResults; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Issue a credit to a card not referenced by the original transaction. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoNonReferencedCredit($DataArray) + { + $DNRCFieldsNVP = '&METHOD=DoNonReferencedCredit'; + $CCDetailsNVP = ''; + $PayerNameNVP = ''; + $PayerInfoNVP = ''; + $BillingAddressNVP = ''; + + // DoNonReferencedCredit Fields + $DNRCFields = isset($DataArray['DNRCFields']) ? $DataArray['DNRCFields'] : array(); + foreach ($DNRCFields as $DNRCFieldsVar => $DNRCFieldsVal) { + $DNRCFieldsNVP .= $DNRCFieldsVal != '' ? '&' . strtoupper($DNRCFieldsVar) . '=' . urlencode($DNRCFieldsVal) : ''; + } + + // CC Details Fields + $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); + foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) { + $CCDetailsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; + } + + // Payer Name Fields + $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); + foreach ($PayerName as $PayerNameVar => $PayerNameVal) { + $PayerNameNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; + } + + // Payer Info Fields + $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); + foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) { + $PayerInfoNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; + } + + // Address Fields (Billing) + $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); + foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) { + $BillingAddressNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DNRCFieldsNVP . $CCDetailsNVP . $PayerNameNVP . $PayerInfoNVP . $BillingAddressNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Process a payment from a buyer's account, which is identified by a previous transaction. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoReferenceTransaction($DataArray) + { + $DRTFieldsNVP = '&METHOD=DoReferenceTransaction'; + $CCDetailsNVP = ''; + $PayerInfoNVP = ''; + $BillingAddressNVP = ''; + $ShippingAddressNVP = ''; + $PaymentDetailsNVP = ''; + $OrderItemsNVP = ''; + + // DoReferenceTransaction Fields + $DRTFields = isset($DataArray['DRTFields']) ? $DataArray['DRTFields'] : array(); + foreach ($DRTFields as $DRTFieldsVar => $DRTFieldsVal) { + $DRTFieldsNVP .= $DRTFieldsVal != '' ? '&' . strtoupper($DRTFieldsVar) . '=' . urlencode($DRTFieldsVal) : ''; + } + + // Ship To Address Fields + $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); + foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) { + $ShippingAddressNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; + } + + // Payment Details Item Type Fields + $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array(); + $n = 0; + foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) { + $CurrentItem = $OrderItems[$OrderItemsVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $OrderItemsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; + } + $n++; + } + + // CC Details Fields + $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); + foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) { + $CCDetailsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; + } + + // PayerInfo Type Fields + $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); + foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) { + $PayerInfoNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; + } + + // Address Fields (Billing) + $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); + foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) { + $BillingAddressNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; + } + + // Payment Details Fields + $PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array(); + foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) { + $PaymentDetailsNVP .= $PaymentDetailsVal != '' ? '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DRTFieldsNVP . $ShippingAddressNVP . $OrderItemsNVP . $CCDetailsNVP . $PayerInfoNVP . $BillingAddressNVP . $PaymentDetailsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Obtain the available balance for a PayPal account. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed balance results, errors and the raw request/response. + */ + function GetBalance($DataArray) + { + $GBFieldsNVP = '&METHOD=GetBalance'; + + // GetBalance Fields + $GBFields = isset($DataArray['GBFields']) ? $DataArray['GBFields'] : array(); + foreach ($GBFields as $GBFieldsVar => $GBFieldsVal) { + $GBFieldsNVP .= $GBFieldsVal != '' ? '&' . strtoupper($GBFieldsVar) . '=' . urlencode($GBFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $GBFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $BalanceResults = array(); + $n = 0; + while (isset($NVPResponseArray['L_AMT' . $n . ''])) { + $LAmt = isset($NVPResponseArray['L_AMT' . $n . '']) ? $NVPResponseArray['L_AMT' . $n . ''] : ''; + $LCurrencyCode = isset($NVPResponseArray['L_CURRENCYCODE' . $n . '']) ? $NVPResponseArray['L_CURRENCYCODE' . $n . ''] : ''; + + $CurrentItem = array( + 'L_AMT' => $LAmt, + 'L_CURRENCYCODE' => $LCurrencyCode + ); + + array_push($BalanceResults, $CurrentItem); + $n++; + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['BALANCERESULTS'] = $BalanceResults; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Obtain your Pal ID, which is the PayPal–assigned merchant account number, and other informaton about your account. + * + * You need the encrypted account number when working with dynamic versions of PayPal buttons and logos. + * + * @access public + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetPalDetails() + { + $GPFieldsNVP = '&METHOD=GetPalDetails'; + + $NVPRequest = $this->NVPCredentials . $GPFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Confirm whether a postal address and postal code match those of the specified PayPal account holder. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function AddressVerify($DataArray) + { + $AVFieldsNVP = '&METHOD=AddressVerify'; + + $AVFields = isset($DataArray['AVFields']) ? $DataArray['AVFields'] : array(); + foreach ($AVFields as $AVFieldsVar => $AVFieldsVal) { + $AVFieldsNVP .= $AVFieldsVal != '' ? '&' . strtoupper($AVFieldsVar) . '=' . urlencode($AVFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $AVFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Accept or deny a pending transaction held by Fraud Management Filters. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function ManagePendingTransactionStatus($DataArray) + { + $MPTSFieldsNVP = '&METHOD=ManagePendingTransactionStatus'; + + $MPTSFields = isset($DataArray['MPTSFields']) ? $DataArray['MPTSFields'] : array(); + foreach ($MPTSFields as $MPTSFieldsVar => $MPTSFieldsVal) { + $MPTSFieldsNVP .= $MPTSFieldsVal != '' ? '&' . strtoupper($MPTSFieldsVar) . '=' . urlencode($MPTSFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $MPTSFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Create a recurring payments profile. + * + * You must invoke the CreateRecurringPaymentsProfile API operation for each + * profile you want to create. The API operation creates a profile and an + * associated billing agreement. + * + * There is a one-to-one correspondence between billing agreements and + * recurring payments profiles. To associate a recurring payments profile + * with its billing agreement, you must ensure that the description in the + * recurring payments profile matches the description of a billing agreement. + * For version 54.0 and later, use SetExpressCheckout to initiate creation of + * a billing agreement. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function CreateRecurringPaymentsProfile($DataArray) + { + $CRPPFieldsNVP = '&METHOD=CreateRecurringPaymentsProfile'; + $OrderItemsNVP = ''; + + $CRPPFields = isset($DataArray['CRPPFields']) ? $DataArray['CRPPFields'] : array(); + foreach ($CRPPFields as $CRPPFieldsVar => $CRPPFieldsVal) { + $CRPPFieldsNVP .= $CRPPFieldsVal != '' ? '&' . strtoupper($CRPPFieldsVar) . '=' . urlencode($CRPPFieldsVal) : ''; + } + + $ProfileDetails = isset($DataArray['ProfileDetails']) ? $DataArray['ProfileDetails'] : array(); + foreach ($ProfileDetails as $ProfileDetailsVar => $ProfileDetailsVal) { + $CRPPFieldsNVP .= $ProfileDetailsVal != '' ? '&' . strtoupper($ProfileDetailsVar) . '=' . urlencode($ProfileDetailsVal) : ''; + } + + $ScheduleDetails = isset($DataArray['ScheduleDetails']) ? $DataArray['ScheduleDetails'] : array(); + foreach ($ScheduleDetails as $ScheduleDetailsVar => $ScheduleDetailsVal) { + $CRPPFieldsNVP .= $ScheduleDetailsVal != '' ? '&' . strtoupper($ScheduleDetailsVar) . '=' . urlencode($ScheduleDetailsVal) : ''; + } + + $BillingPeriod = isset($DataArray['BillingPeriod']) ? $DataArray['BillingPeriod'] : array(); + foreach ($BillingPeriod as $BillingPeriodVar => $BillingPeriodVal) { + $CRPPFieldsNVP .= $BillingPeriodVal != '' ? '&' . strtoupper($BillingPeriodVar) . '=' . urlencode($BillingPeriodVal) : ''; + } + + $ActivationDetails = isset($DataArray['ActivationDetails']) ? $DataArray['ActivationDetails'] : array(); + foreach ($ActivationDetails as $ActivationDetailsVar => $ActivationDetailsVal) { + $CRPPFieldsNVP .= $ActivationDetailsVal != '' ? '&' . strtoupper($ActivationDetailsVar) . '=' . urlencode($ActivationDetailsVal) : ''; + } + + $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); + foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) { + $CRPPFieldsNVP .= $CCDetails != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; + } + + $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); + foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) { + $CRPPFieldsNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; + } + + $PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array(); + foreach ($PayerName as $PayerNameVar => $PayerNameVal) { + $CRPPFieldsNVP .= $PayerNameVal != '' ? '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal) : ''; + } + + $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); + foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) { + $CRPPFieldsNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; + } + + $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); + foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) { + $CRPPFieldsNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; + } + + // Payment Details Item Type Fields + $OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array(); + $n = 0; + $m = 0; + foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) { + $CurrentItem = $OrderItems[$OrderItemsVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $OrderItemsNVP .= $CurrentItemVal != '' ? '&L_PAYMENTREQUEST_' . $n . '_' . strtoupper($CurrentItemVar) . $m . '=' . urlencode($CurrentItemVal) : ''; + } + $m++; + } + + $NVPRequest = $this->NVPCredentials . $CRPPFieldsNVP . $OrderItemsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Obtain information about a recurring payments profile. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetRecurringPaymentsProfileDetails($DataArray) + { + $GRPPDFieldsNVP = '&METHOD=GetRecurringPaymentsProfileDetails'; + + $GRPPDFields = isset($DataArray['GRPPDFields']) ? $DataArray['GRPPDFields'] : array(); + foreach ($GRPPDFields as $GRPPDFieldsVar => $GRPPDFieldsVal) { + $GRPPDFieldsNVP .= $GRPPDFieldsVal != '' ? '&' . strtoupper($GRPPDFieldsVar) . '=' . urlencode($GRPPDFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $GRPPDFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Cancel, suspend, or reactivate a recurring payments profile. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function ManageRecurringPaymentsProfileStatus($DataArray) + { + $MRPPSFieldsNVP = '&METHOD=ManageRecurringPaymentsProfileStatus'; + + $MRPPSFields = isset($DataArray['MRPPSFields']) ? $DataArray['MRPPSFields'] : array(); + foreach ($MRPPSFields as $MRPPSFieldsVar => $MRPPSFieldsVal) { + $MRPPSFieldsNVP .= $MRPPSFieldsVal != '' ? '&' . strtoupper($MRPPSFieldsVar) . '=' . urlencode($MRPPSFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $MRPPSFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Bill the buyer for the outstanding balance associated with a recurring payments profile. + * + * To bill the outstanding amount: + * - The profile status must be active or suspended. + * - The profile must have a non-zero outstanding balance. + * - The amount of the payment cannot exceed the outstanding amount for the profile. + * + * The BillOutstandingAmount call cannot be within 24 hours of a regularly scheduled payment for this profile. + * + * If another outstanding balance payment is already queued, an API error is returned. + * + * You will be informed by IPN about the success or failure of the outstanding payment. + * For profiles created using Express Checkout, the buyer will receive an email notification of the payment. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function BillOutstandingAmount($DataArray) + { + $BOAFieldsNVP = '&METHOD=BillOutstandingAmount'; + + $BOAFields = isset($DataArray['BOAFields']) ? $DataArray['BOAFields'] : array(); + foreach ($BOAFields as $BOAFieldsVar => $BOAFieldsVal) { + $BOAFieldsNVP .= $BOAFieldsVal != '' ? '&' . strtoupper($BOAFieldsVar) . '=' . urlencode($BOAFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $BOAFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Update a recurring payments profile. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function UpdateRecurringPaymentsProfile($DataArray) + { + $URPPFieldsNVP = '&METHOD=UpdateRecurringPaymentsProfile'; + + $URPPFields = isset($DataArray['URPPFields']) ? $DataArray['URPPFields'] : array(); + foreach ($URPPFields as $URPPFieldsVar => $URPPFieldsVal) { + $URPPFieldsNVP .= $URPPFieldsVal != '' ? '&' . strtoupper($URPPFieldsVar) . '=' . urlencode($URPPFieldsVal) : ''; + } + + $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array(); + foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) { + $URPPFieldsNVP .= $BillingAddressVal != '' ? '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal) : ''; + } + + $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); + foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) { + $URPPFieldsNVP .= $ShippingAddressVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; + } + + $BillingPeriod = isset($DataArray['BillingPeriod']) ? $DataArray['BillingPeriod'] : array(); + foreach ($BillingPeriod as $BillingPeriodVar => $BillingPeriodVal) { + $URPPFieldsNVP .= $BillingPeriodVal != '' ? '&' . strtoupper($BillingPeriodVar) . '=' . urlencode($BillingPeriodVal) : ''; + } + + $CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array(); + foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) { + $URPPFieldsNVP .= $CCDetailsVal != '' ? '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal) : ''; + } + + $PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array(); + foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) { + $URPPFieldsNVP .= $PayerInfoVal != '' ? '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $URPPFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Obtain information about a recurring payments profile. + * + * @access public + * @param string $ProfileID The ID of a recurring payments profile. + * @return mixed[] Returns an array structure consisting of the full result as well as the parsed profile status. + */ + function GetRecurringPaymentsProfileStatus($ProfileID) + { + $GRPPDFields = array('profileid' => $ProfileID); + $PayPalRequestData = array('GRPPDFields' => $GRPPDFields); + + $PayPalResult = $this->GetRecurringPaymentsProfileDetails($PayPalRequestData); + $PayPalErrors = $PayPalResult['ERRORS']; + $ProfileStatus = isset($PayPalResult['STATUS']) ? $PayPalResult['STATUS'] : 'Unknown'; + + $ResponseArray = array( + 'PayPalResult' => $PayPalResult, + 'ProfileStatus' => $ProfileStatus + ); + + return $ResponseArray; + } + + /** + * Create a billing agreement with a PayPal account holder. + * + * CreateBillingAgreement is only valid for reference transactions. + * + * @access public + * @param string $Token A token returned from a previous SetExpressCheckout request. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + * + */ + function CreateBillingAgreement($Token) + { + $CBAFieldsNVP = '&METHOD=CreateBillingAgreement&TOKEN=' . urlencode($Token); + + $NVPRequest = $this->NVPCredentials . $CBAFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Initiate the creation of a billing agreement. + * + * When using Express Checkout with version 54.0 or later of the API, + * do not use SetCustomerBillingAgreement and GetBillingAgreementCustomerDetails. + * Instead, use SetExpressCheckout and set the amount value to zero. Call + * GetExpressCheckoutDetails to obtain information about the buyer's checkout + * status. Then use the CreateBillingAgreement API to create the abilling agreement. + * + * @access public + * @deprecated No longer used in PayPal API version 54.0 or higher. + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function SetCustomerBillingAgreement($DataArray) + { + $SCBAFieldsNVP = '&METHOD=SetCustomerBillingAgreement'; + $BillingAgreementsNVP = ''; + + $SCBAFields = isset($DataArray['SCBAFields']) ? $DataArray['SCBAFields'] : array(); + foreach ($SCBAFields as $SCBAFieldsVar => $SCBAFieldsVal) { + $SCBAFieldsNVP .= $SCBAFieldsVal != '' ? '&' . strtoupper($SCBAFieldsVar) . '=' . urlencode($SCBAFieldsVal) : ''; + } + + $BillingAgreements = isset($DataArray['BillingAgreements']) ? $DataArray['BillingAgreements'] : array(); + $n = 0; + foreach ($BillingAgreements as $BillingAgreementVar => $BillingAgreementVal) { + $CurrentItem = $BillingAgreements[$BillingAgreementVar]; + foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) { + $BillingAgreementsNVP .= $CurrentItemVal != '' ? '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal) : ''; + } + $n++; + } + + $NVPRequest = $this->NVPCredentials . $SCBAFieldsNVP . $BillingAgreementsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Obtain information about a billing agreement's PayPal account holder + * + * When using Express Checkout with version 54.0 or later of the API, + * do not use SetCustomerBillingAgreement and GetBillingAgreementCustomerDetails. + * Instead, use SetExpressCheckout and set the amount value to zero. Call + * GetExpressCheckoutDetails to obtain information about the buyer's checkout + * status. Then use the CreateBillingAgreement API to create the abilling agreement. + + * @access public + * @deprecated No longer used in PayPal API version 54.0 or higher. + * @param string $Token Token returned by a previous SetCustomerBillingAgreement request. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetBillingAgreementCustomerDetails($Token) + { + $GBACDFieldsNVP = '&METHOD=GetBillingAgreementCustomerDetails&TOKEN=' . $Token; + + $NVPRequest = $this->NVPCredentials . $GBACDFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Update or delete a billing agreement. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function BillAgreementUpdate($DataArray) + { + $BAUFieldsNVP = '&METHOD=BillAgreementUpdate'; + + $BAUFields = isset($DataArray['BAUFields']) ? $DataArray['BAUFields'] : array(); + foreach ($BAUFields as $BAUFieldsVar => $BAUFieldsVal) { + $BAUFieldsNVP .= $BAUFieldsVal != '' ? '&' . strtoupper($BAUFieldsVar) . '=' . urlencode($BAUFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $BAUFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Setup the mobile checkout flow. + * + * @access public + * @deprecated No longer used by PayPal. Use Express Checkout instead. + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function SetMobileCheckout($DataArray) + { + $SMCFieldsNVP = '&METHOD=SetMobileCheckout'; + + $SMCFields = isset($DataArray['SMCFields']) ? $DataArray['SMCFields'] : array(); + foreach ($SMCFields as $SMCFieldsVar => $SMCFieldsVal) { + $SMCFieldsNVP .= $SMCFieldsVal != '' ? '&' . strtoupper($SMCFieldsVar) . '=' . urlencode($SMCFieldsVal) : ''; + } + + $ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); + foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) { + $SMCFieldsNVP .= $SMCFieldsVal != '' ? '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $SMCFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Finalize and process the sale from a mobile checkout flow. + * + * @access public + * @deprecated No longer used by PayPal. Use Express Checkout instead. + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function DoMobileCheckoutPayment($DataArray) + { + $DMCPFieldsNVP = '&METHOD=DoMobileCheckoutPayment'; + + $DMCPFields = isset($DataArray['DMCPFields']) ? $DataArray['DMCPFields'] : array(); + foreach ($DMCPFields as $DMCPFieldsVar => $DMCPFieldsVal) { + $DMCPFieldsNVP .= $DMCPFieldsVal != '' ? '&' . strtoupper($DMCPFieldsVar) . '=' . urlencode($DMCPFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $DMCPFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Set authorization params + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function SetAuthFlowParam($DataArray) + { + $SetAuthFlowParamFieldsNVP = '&METHOD=SetAuthFlowParam'; + + // SetAuthFlowParam Fields + $SetAuthFlowParamFields = isset($DataArray['SetAuthFlowParamFields']) ? $DataArray['SetAuthFlowParamFields'] : array(); + foreach ($SetAuthFlowParamFields as $SetAuthFlowParamFieldsVar => $SetAuthFlowParamFieldsVal) { + $SetAuthFlowParamFieldsNVP .= $SetAuthFlowParamFieldsVal != '' ? '&' . strtoupper($SetAuthFlowParamFieldsVar) . '=' . urlencode($SetAuthFlowParamFieldsVal) : ''; + } + + // ShippingAddress Fields + $ShippingAddressFields = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array(); + foreach ($ShippingAddressFields as $ShippingAddressFieldsVar => $ShippingAddressFieldsVal) { + $SetAuthFlowParamFieldsNVP .= $ShippingAddressFieldsVal != '' ? '&' . strtoupper($ShippingAddressFieldsVar) . '=' . urlencode($ShippingAddressFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $SetAuthFlowParamFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $Token = isset($NVPResponseArray['TOKEN']) ? $NVPResponseArray['TOKEN'] : ''; + $RedirectURL = $Token != '' ? 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_account-authenticate-login&token=' . $Token : ''; + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REDIRECTURL'] = $RedirectURL; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Get authorization details + * + * @access public + * @param string $Token + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetAuthDetails($Token) + { + $GetAuthDetailsFieldsNVP = '&METHOD=GetAuthDetails&TOKEN=' . $Token; + + $NVPRequest = $this->NVPCredentials . $GetAuthDetailsFieldsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + + /** + * Retrieve the current API permissions granted for the application. + * + * @access public + * @deprecated No longer used by PayPal. + * @param string $Token + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function GetAccessPermissionsDetails($Token) + { + $GetAccessPermissionsDetailsNVP = '&METHOD=GetAccessPermissionsDetails&TOKEN=' . $Token; + + $NVPRequest = $this->NVPCredentials . $GetAccessPermissionsDetailsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $Permissions = array(); + $n = 0; + while (isset($NVPResponseArray['L_ACCESSPERMISSIONNAME' . $n . ''])) { + $LName = isset($NVPResponseArray['L_ACCESSPERMISSIONNAME' . $n . '']) ? $NVPResponseArray['L_ACCESSPERMISSIONNAME' . $n . ''] : ''; + $LStatus = isset($NVPResponseArray['L_ACCESSPERMISSIONSTATUS' . $n . '']) ? $NVPResponseArray['L_ACCESSPERMISSIONSTATUS' . $n . ''] : ''; + + $CurrentItem = array( + 'L_ACCESSPERMISSIONNAME' => $LName, + 'L_ACCESSPERMISSIONSTATUS' => $LStatus + ); + + array_push($ActivePermissions, $CurrentItem); + $n++; + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['Permissions'] = $Permissions; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Set the access permissions for an application on a 3rd party user's account. + * + * @access public + * @deprecated No longer used by PayPal. + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function SetAccessPermissions($DataArray) + { + $SetAccessPermissionsNVP = '&METHOD=SetAccessPermissions'; + + // SetAccessPermissions Fields + $SetAccessPermissionsFields = isset($DataArray['SetAccessPermissionsFields']) ? $DataArray['SetAccessPermissionsFields'] : array(); + foreach ($SetAccessPermissionsFields as $SetAccessPermissionsFieldsVar => $SetAccessPermissionsFieldsVal) { + $SetAccessPermissionsNVP .= $SetAccessPermissionsFieldsVal != '' ? '&' . strtoupper($SetAccessPermissionsFieldsVar) . '=' . urlencode($SetAccessPermissionsFieldsVal) : ''; + } + + $n = 0; + $RequiredPermissions = isset($DataArray['RequiredPermissions']) ? $DataArray['RequiredPermissions'] : array(); + foreach ($RequiredPermissions as $RequiredPermission) { + $SetAccessPermissionsNVP .= '&L_REQUIREDACCESSPERMISSIONS' . $n . '=' . urlencode($RequiredPermission); + $n++; + } + + $n = 0; + $OptionalPermissions = isset($DataArray['OptionalPermissions']) ? $DataArray['OptionalPermissions'] : array(); + foreach ($OptionalPermissions as $OptionalPermission) { + $SetAccessPermissionsNVP .= '&L_OPTIONALACCESSPERMISSIONS' . $n . '=' . urlencode($OptionalPermission); + $n++; + } + + $NVPRequest = $this->NVPCredentials . $SetAccessPermissionsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $Token = isset($NVPResponseArray['TOKEN']) ? $NVPResponseArray['TOKEN'] : ''; + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + if ($this->Sandbox) { + $RedirectURL = $Token != '' ? 'https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-login&token=' . $Token : ''; + $LogoutRedirectURL = $Token != '' ? 'https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-logout&token=' . $Token : ''; + } else { + $RedirectURL = $Token != '' ? 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-login&token=' . $Token : ''; + $LogoutRedirectURL = $Token != '' ? 'https://www.paypal.com/us/cgi-bin/webscr?cmd=_access-permission-logout&token=' . $Token : ''; + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REDIRECTURL'] = $RedirectURL; + $NVPResponseArray['LOGOUTREDIRECTURL'] = $LogoutRedirectURL; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Update the access permissions for an application on a 3rd party user's account. + * + * @access public + * @deprecated No longer used by PayPal. + * @param string $PayerID Payer ID of the PayPal user. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function UpdateAccessPermissions($PayerID) + { + $UpdateAcccessPermissionsNVP = '&METHOD=UpdateAccessPermissions&PAYERID=' . $PayerID; + + $NVPRequest = $this->NVPCredentials . $UpdateAcccessPermissionsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + + /** + * Obtain a list of your hosted PayPal Payments Standard buttons. + * + * The request contains optional fields that are not currently used. + * All buttons are automatically requested. + * + * @access public + * @param mixed[] $DataArray Array structure of request data. + * @return mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function BMButtonSearch($DataArray) + { + $BMButtonSearchNVP = '&METHOD=BMButtonSearch'; + + // BMButtonSearch Fields + $BMButtonSearchFields = isset($DataArray['BMButtonSearchFields']) ? $DataArray['BMButtonSearchFields'] : array(); + foreach ($BMButtonSearchFields as $BMButtonSearchFieldsVar => $BMButtonSearchFieldsVal) { + $BMButtonSearchNVP .= $BMButtonSearchFieldsVal != '' ? '&' . strtoupper($BMButtonSearchFieldsVar) . '=' . urlencode($BMButtonSearchFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $BMButtonSearchNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + + $SearchResults = array(); + $n = 0; + while (isset($NVPResponseArray['L_HOSTEDBUTTONID' . $n . ''])) { + $LHostedButtonID = isset($NVPResponseArray['L_HOSTEDBUTTONID' . $n . '']) ? $NVPResponseArray['L_HOSTEDBUTTONID' . $n . ''] : ''; + $LButtonType = isset($NVPResponseArray['L_BUTTONTYPE' . $n . '']) ? $NVPResponseArray['L_BUTTONTYPE' . $n . ''] : ''; + $LItemName = isset($NVPResponseArray['L_ITEMNAME' . $n . '']) ? $NVPResponseArray['L_ITEMNAME' . $n . ''] : ''; + $LModifyDate = isset($NVPResponseArray['L_MODIFYDATE' . $n . '']) ? $NVPResponseArray['L_MODIFYDATE' . $n . ''] : ''; + + $CurrentItem = array( + 'L_HOSTEDBUTTONID' => $LHostedButtonID, + 'L_BUTTONTYPE' => $LButtonType, + 'L_ITEMNAME' => $LItemName, + 'L_MODIFYDATE' => $LModifyDate + ); + + array_push($SearchResults, $CurrentItem); + $n++; + } + + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['SEARCHRESULTS'] = $SearchResults; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + + return $NVPResponseArray; + } + + /** + * Use the BMCreateButton API operation to create a PayPal Payments Standard button. + * You can create either a button that is hosted on PayPal or a non-hosted button. + * + * @param $DataArray + * @return \mixed[] + */ + function BMCreateButton($DataArray) + { + $BMCreateButtonNVP = '&METHOD=BMCreateButton'; +// BMCreateButton Fields + $BMCreateButtonFields = isset($DataArray['BMCreateButtonFields']) ? $DataArray['BMCreateButtonFields'] : array(); + foreach ($BMCreateButtonFields as $BMCreateButtonFieldsVar => $BMCreateButtonFieldsVal) { + $BMCreateButtonNVP .= $BMCreateButtonFieldsVal != '' ? '&' . strtoupper($BMCreateButtonFieldsVar) . '=' . urlencode($BMCreateButtonFieldsVal) : ''; + } + + $n = 0; + $BMButtonVars = isset($DataArray['BMButtonVars']) ? $DataArray['BMButtonVars'] : array(); + $BMButtonVars['bn'] = $this->APIButtonSource; + foreach ($BMButtonVars as $BMButtonVarName => $BMButtonVarValue) { + $BMCreateButtonNVP .= $BMButtonVarValue != '' ? "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue) : ""; + if ($BMButtonVarValue != '') { + $BMCreateButtonNVP .= "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue); + $n++; + } + } + + $n = 0; + $BMButtonOptions = isset($DataArray['BMButtonOptions']) ? $DataArray['BMButtonOptions'] : array(); + foreach ($BMButtonOptions as $BMButtonOption) { + $n_selection = 0; + $ButtonOptionName = $BMButtonOption['name']; + $ButtonOptionSelections = $BMButtonOption['selections']; + $BMCreateButtonNVP .= '&OPTION' . $n . 'NAME=' . $ButtonOptionName; + foreach ($ButtonOptionSelections as $ButtonOptionSelection) { + $BMCreateButtonNVP .= $ButtonOptionSelection['value'] != '' ? '&L_OPTION' . $n . 'SELECT' . $n_selection . '=' . urlencode($ButtonOptionSelection['value']) : ''; + $BMCreateButtonNVP .= $ButtonOptionSelection['price'] != '' ? '&L_OPTION' . $n . 'PRICE' . $n_selection . '=' . urlencode($ButtonOptionSelection['price']) : ''; + $BMCreateButtonNVP .= $ButtonOptionSelection['type'] != '' ? '&L_OPTION' . $n . 'TYPE' . $n_selection . '=' . urlencode($ButtonOptionSelection['type']) : ''; + $n_selection++; + } + + $n++; + } + + $NVPRequest = $this->NVPCredentials . $BMCreateButtonNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Use the BMUpdateButton API operation to modify a PayPal Payments Standard button that is hosted on PayPal. + * This operation replaces all fields in the specified button; therefore, you must specify a value for + * each field you want to include for the button, whether or not it changed. + * + * @param $DataArray + * @return \mixed[] + */ + function BMUpdateButton($DataArray) + { + $BMUpdateButtonNVP = '&METHOD=BMUpdateButton'; +// BMUpdateButton Fields + $BMUpdateButtonFields = isset($DataArray['BMUpdateButtonFields']) ? $DataArray['BMUpdateButtonFields'] : array(); + foreach ($BMUpdateButtonFields as $BMUpdateButtonFieldsVar => $BMUpdateButtonFieldsVal) { + $BMUpdateButtonNVP .= $BMUpdateButtonFieldsVal != '' ? '&' . strtoupper($BMUpdateButtonFieldsVar) . '=' . urlencode($BMUpdateButtonFieldsVal) : ''; + } + + $n = 0; + $BMButtonVars = isset($DataArray['BMButtonVars']) ? $DataArray['BMButtonVars'] : array(); + $BMButtonVars['bn'] = $this->APIButtonSource; + foreach ($BMButtonVars as $BMButtonVarName => $BMButtonVarValue) { + $BMUpdateButtonNVP .= $BMButtonVarValue != '' ? "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue) : ""; + if ($BMButtonVarValue != '') { + $BMUpdateButtonNVP .= "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue); + $n++; + } + } + + $n = 0; + $BMButtonOptions = isset($DataArray['BMButtonOptions']) ? $DataArray['BMButtonOptions'] : array(); + foreach ($BMButtonOptions as $BMButtonOption) { + $n_selection = 0; + $ButtonOptionName = $BMButtonOption['name']; + $ButtonOptionSelections = $BMButtonOption['selections']; + $BMUpdateButtonNVP .= '&OPTION' . $n . 'NAME=' . $ButtonOptionName; + foreach ($ButtonOptionSelections as $ButtonOptionSelection) { + $BMUpdateButtonNVP .= $ButtonOptionSelection['value'] != '' ? '&L_OPTION' . $n . 'SELECT' . $n_selection . '=' . urlencode($ButtonOptionSelection['value']) : ''; + $BMUpdateButtonNVP .= $ButtonOptionSelection['price'] != '' ? '&L_OPTION' . $n . 'PRICE' . $n_selection . '=' . urlencode($ButtonOptionSelection['price']) : ''; + $BMUpdateButtonNVP .= $ButtonOptionSelection['type'] != '' ? '&L_OPTION' . $n . 'TYPE' . $n_selection . '=' . urlencode($ButtonOptionSelection['type']) : ''; + $n_selection++; + } + + $n++; + } + + $NVPRequest = $this->NVPCredentials . $BMUpdateButtonNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Use the BMGetButtonDetails API operation to obtain information about a hosted PayPal Payments Standard button. + * You can use this information to set the fields that have not changed when updating a button. + * + * @param $HostedButtonID + * @return mixed[] $NVPResponseArray Returns an array structure of the PayPal HTTP response params as well as parsed errors and the raw request/response. + */ + function BMGetButtonDetails($HostedButtonID) + { + $BMGetButtonDetailsNVP = '&METHOD=BMGetButtonDetails&HOSTEDBUTTONID=' . $HostedButtonID; + $NVPRequest = $this->NVPCredentials . $BMGetButtonDetailsNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Use the BMGetInventory API operation to determine the inventory levels and other inventory-related + * information for a button and menu items associated with the button. Typically, you call BMGetInventory + * to obtain field values before calling BMSetInventory to change the inventory levels. + * + * @param $DataArray + * @return \mixed[] + */ + function BMGetInventory($DataArray) + { + $BMGetInventoryNVP = '&METHOD=BMGetInventory'; +// BMGetInventory Fields + $BMGetInventoryFields = isset($DataArray['BMGetInventoryFields']) ? $DataArray['BMGetInventoryFields'] : array(); + foreach ($BMGetInventoryFields as $BMGetInventoryFieldsVar => $BMGetInventoryFieldsVal) { + $BMGetInventoryNVP .= $BMGetInventoryFieldsVal != '' ? '&' . strtoupper($BMGetInventoryFieldsVar) . '=' . urlencode($BMGetInventoryFieldsVal) : ''; + } + + // DigitalDownloadKeys + $n = 0; + $DigitalDownloadKeys = isset($DataArray['DigitalDownloadKeys']) ? $DataArray['DigitalDownloadKeys'] : array(); + foreach ($DigitalDownloadKeys as $DigitalDownloadKey) { + $BMGetInventoryNVP .= '&L_DIGITALDOWNLOADKEYS' . $n . '=' . urlencode($DigitalDownloadKey); + $n++; + } + + $NVPRequest = $this->NVPCredentials . $BMGetInventoryNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Use the BMManageButtonStatus API operation to change the status of a hosted button. Currently, you can only delete a button. + * + * @param $DataArray + * @return \mixed[] + */ + function BMManageButtonStatus($DataArray) + { + $BMManageButtonStatusNVP = '&METHOD=BMManageButtonStatus'; +// BMManageButtonStatus Fields + $BMManageButtonStatusFields = isset($DataArray['BMManageButtonStatusFields']) ? $DataArray['BMManageButtonStatusFields'] : array(); + foreach ($BMManageButtonStatusFields as $BMManageButtonStatusFieldsVar => $BMManageButtonStatusFieldsVal) { + $BMManageButtonStatusNVP .= $BMManageButtonStatusFieldsVal != '' ? '&' . strtoupper($BMManageButtonStatusFieldsVar) . '=' . urlencode($BMManageButtonStatusFieldsVal) : ''; + } + + $NVPRequest = $this->NVPCredentials . $BMManageButtonStatusNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + /** + * Use the BMSetInventory API operation to set the inventory level and inventory management + * features for the specified button. When you set the inventory level for a button, + * PayPal can track inventory, calculate the gross profit associated with sales, send you + * an alert when inventory drops below a specified quantity, and manage sold out conditions. + * + * @param $DataArray + * @return \mixed[] + */ + function BMSetInventory($DataArray) + { + $BMSetInventoryNVP = '&METHOD=BMSetInventory'; +// BMSetInventory Fields + $BMSetInventoryFields = isset($DataArray['BMSetInventoryFields']) ? $DataArray['BMSetInventoryFields'] : array(); + foreach ($BMSetInventoryFields as $BMSetInventoryFieldsVar => $BMSetInventoryFieldsVal) { + $BMSetInventoryNVP .= $BMSetInventoryFieldsVal != '' ? '&' . strtoupper($BMSetInventoryFieldsVar) . '=' . urlencode($BMSetInventoryFieldsVal) : ''; + } + + // DigitalDownloadKeys + $n = 0; + $DigitalDownloadKeys = isset($DataArray['DigitalDownloadKeys']) ? $DataArray['DigitalDownloadKeys'] : array(); + foreach ($DigitalDownloadKeys as $DigitalDownloadKey) { + $BMSetInventoryNVP .= '&L_DIGITALDOWNLOADKEYS' . $n . '=' . urlencode($DigitalDownloadKey); + $n++; + } + + // ItemTrackingDetails + $ItemTrackingDetailsFields = isset($DataArray['ItemTrackingDetails']) ? $DataArray['ItemTrackingDetails'] : array(); + foreach ($ItemTrackingDetailsFields as $ItemTrackingDetailsFieldsVar => $ItemTrackingDetailsFieldsVal) { + $BMSetInventoryNVP .= $ItemTrackingDetailsFieldsVal != '' ? '&' . strtoupper($ItemTrackingDetailsFieldsVar) . '=' . urlencode($ItemTrackingDetailsFieldsVal) : ''; + } + + // OptionTrackingDetails + $n = 0; + $OptionTrackingDetails = isset($DataArray['OptionTrackingDetails']) ? $DataArray['OptionTrackingDetails'] : array(); + foreach ($OptionTrackingDetails as $OptionTrackingDetail) { + $BMSetInventoryNVP .= '&L_OPTIONNUMBER' . $n . '=' . urlencode($OptionTrackingDetail['number']); + $BMSetInventoryNVP .= '&L_OPTIONQTY' . $n . '=' . urlencode($OptionTrackingDetail['qty']); + $BMSetInventoryNVP .= '&L_OPTIONSELECT' . $n . '=' . urlencode($OptionTrackingDetail['select']); + $BMSetInventoryNVP .= '&L_OPTIONQTYDELTA' . $n . '=' . urlencode($OptionTrackingDetail['qtydelta']); + $BMSetInventoryNVP .= '&L_OPTIONALERT' . $n . '=' . urlencode($OptionTrackingDetail['alert']); + $BMSetInventoryNVP .= '&L_OPTIONCOST' . $n . '=' . urlencode($OptionTrackingDetail['cost']); + $n++; + } + + $NVPRequest = $this->NVPCredentials . $BMSetInventoryNVP; + $NVPResponse = $this->CURLRequest($NVPRequest); + $NVPRequestArray = $this->NVPToArray($NVPRequest); + $NVPResponseArray = $this->NVPToArray($NVPResponse); + $Errors = $this->GetErrors($NVPResponseArray); + $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $this->MaskAPIResult($NVPRequest)); + $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $NVPResponse); + $NVPResponseArray['ERRORS'] = $Errors; + $NVPResponseArray['REQUESTDATA'] = $NVPRequestArray; + $NVPResponseArray['RAWREQUEST'] = $NVPRequest; + $NVPResponseArray['RAWRESPONSE'] = $NVPResponse; + return $NVPResponseArray; + } + + public function TPV_Parse_Request($result_data, $request_data, $product_id = 1, $sandbox = false, $is_nvp = true, $payment_method = null) + { + $request_param = array(); + if (isset($result_data) && is_array($result_data) && !empty($result_data['CURL_ERROR'])) { + return $result_data; + } else { + if ($is_nvp) { + $result = $this->NVPToArray($result_data); + $request = $this->NVPToArray($request_data); + } else { + $result = $result_data; + $request = $request_data; + } + if (is_array($result) && isset($result['PNREF'])) { + $request['METHOD'] = 'ProcessTransaction'; + } + if ($payment_method == 'PayPal_Rest') { + $request['METHOD'] = 'PayPal_Rest'; + } + if (isset($request['METHOD']) && !empty($request['METHOD']) && in_array($request['METHOD'], $this->allow_method)) { + $request_param['site_url'] = ''; + $request_param['merchant_id'] = ''; + $request_param['type'] = $request['METHOD']; + if (is_array($result)) { + $request_param['status'] = isset($result['ACK']) ? $result['ACK'] : ''; + } + $request_param['mode'] = ($sandbox) ? 'sandbox' : 'live'; + $request_param['product_id'] = $product_id; + $request_param['merchant_id'] = ''; + if ($request['METHOD'] == 'DoExpressCheckoutPayment') { + $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; + $request_param['transaction_id'] = isset($result['PAYMENTINFO_0_TRANSACTIONID']) ? $result['PAYMENTINFO_0_TRANSACTIONID'] : ''; + $request_param['amount'] = isset($result['PAYMENTINFO_0_AMT']) ? $result['PAYMENTINFO_0_AMT'] : '0.00'; + $this->TPV_Send_Request($request_param); + } elseif ($request['METHOD'] == 'DoDirectPayment') { + $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; + $request_param['transaction_id'] = isset($result['TRANSACTIONID']) ? $result['TRANSACTIONID'] : ''; + $request_param['amount'] = isset($result['AMT']) ? $result['AMT'] : '0.00'; + $this->TPV_Send_Request($request_param); + } elseif ($request['METHOD'] == 'DoCapture') { + $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; + $request_param['transaction_id'] = isset($result['TRANSACTIONID']) ? $result['TRANSACTIONID'] : ''; + $request_param['amount'] = isset($result['AMT']) ? $result['AMT'] : '0.00'; + $this->TPV_Send_Request($request_param); + } elseif ($request['METHOD'] == 'ProcessTransaction') { + if (isset($result['RESULT']) && ( $result['RESULT'] == 0 )) { + $request_param['status'] = 'Success'; + } else { + $request_param['status'] = 'Failure'; + } + $request_param['correlation_id'] = isset($result['CORRELATIONID']) ? $result['CORRELATIONID'] : ''; + $request_param['transaction_id'] = isset($result['PNREF']) ? $result['PNREF'] : ''; + $request_param['amount'] = isset($result['AMT']) ? $result['AMT'] : '0.00'; + $this->TPV_Send_Request($request_param); + } elseif ($request['METHOD'] == 'PayPal_Rest') { + $request_param['correlation_id'] = ''; + if (!empty($result->purchase_units[0]['payments']['captures'][0]['amount']['value'])) { + $request_param['amount'] = $result->purchase_units[0]['payments']['captures'][0]['amount']['value']; + $request_param['status'] = 'Success'; + $request_param['transaction_id'] = $result->purchase_units[0]['payments']['captures'][0]['id']; + } elseif (!empty($result->purchase_units[0]['payments']['authorizations'][0]['amount']['value'])) { + $request_param['amount'] = $result->purchase_units[0]['payments']['authorizations'][0]['amount']['value']; + $request_param['status'] = 'Success'; + $request_param['transaction_id'] = $result->purchase_units[0]['payments']['authorizations'][0]['id']; + } elseif (!empty($result['id'])) { + $request_param['amount'] = !empty($result['transactions'][0]['amount']['total']) ? $result['transactions'][0]['amount']['total'] : ''; + $request_param['status'] = 'Success'; + $request_param['transaction_id'] = isset($result['transactions'][0]['related_resources'][0]['sale']['id']) ? $result['transactions'][0]['related_resources'][0]['sale']['id'] : ''; + } else { + $request_param['status'] = 'Failure'; + } + $this->TPV_Send_Request($request_param); + } + } + } + return $result_data; + } + + function TPV_Send_Request($request_param) + { + try { + $payment_type = $request_param['type']; + $amount = $request_param['amount']; + $status = $request_param['status']; + $site_url = $request_param['site_url']; + $payment_mode = $request_param['mode']; + $merchant_id = $request_param['merchant_id']; + $correlation_id = $request_param['correlation_id']; + $transaction_id = $request_param['transaction_id']; + $product_id = $request_param['product_id']; + $params = [ + "product_id" => $product_id, + "type" => $payment_type, + "amount" => $amount, + "status" => $status, + "site_url" => $site_url, + "mode" => $payment_mode, + "merchant_id" => $merchant_id, + "correlation_id" => $correlation_id, + "transaction_id" => $transaction_id + ]; + $curl = curl_init(); + curl_setopt($curl, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/json; charset=utf-8', + 'x-api-key: ' . $this->api_key, + 'Content-Length: ' . strlen(json_encode($params)) + )); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_URL, $this->api_url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params)); + curl_exec($curl); + } catch (Exception $ex) { + } + } +} From e68147be0bff1b5d10f77c9bb5922cac1ad8c5ab Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Thu, 9 Oct 2025 16:47:18 +0530 Subject: [PATCH 009/146] Remove Unwanted File as now --- samples/rest/GetBalance.php | 28 ---------------------------- 1 file changed, 28 deletions(-) delete mode 100644 samples/rest/GetBalance.php diff --git a/samples/rest/GetBalance.php b/samples/rest/GetBalance.php deleted file mode 100644 index 6936cc9c..00000000 --- a/samples/rest/GetBalance.php +++ /dev/null @@ -1,28 +0,0 @@ - $sandbox, - 'APIMode' => $api_mode, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - ); - -$PayPal = new angelleye\PayPal\PayPal($PayPalConfig); - -// Prepare request arrays -$GBFields = array('returnallcurrencies' => ''); -$PayPalRequestData = array('GBFields'=>$GBFields); - -// Pass data into class for processing with PayPal and load the response array into $PayPalResult -$PayPalResult = $PayPal->GetBalance($PayPalRequestData); - -// Write the contents of the response array to the screen for demo purposes. -echo '
';
-print_r($PayPalResult);

From 8094575bae90662e9dbc3524fb98a1c24d2d4921 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Thu, 9 Oct 2025 16:50:17 +0530
Subject: [PATCH 010/146] Remove Unwanted Code from Classes

---
 src/angelleye/PayPal/PayPal.php        | 16 ----------------
 src/angelleye/PayPal/PayPalClassic.php |  9 ---------
 src/angelleye/PayPal/PayPalREST.php    |  5 -----
 3 files changed, 30 deletions(-)

diff --git a/src/angelleye/PayPal/PayPal.php b/src/angelleye/PayPal/PayPal.php
index 590aca94..c396dc42 100755
--- a/src/angelleye/PayPal/PayPal.php
+++ b/src/angelleye/PayPal/PayPal.php
@@ -72,20 +72,4 @@ public static function init(array $config = [])
                 throw new \InvalidArgumentException("Invalid PayPal API mode: $apiMode");
         }
     }
-
-    /**
-     * Common interface that both Classic and REST must implement
-     */
-//     abstract public function SetExpressCheckout(array $params);
-//     abstract public function GetExpressCheckoutDetails($token);
-//     abstract public function DoExpressCheckoutPayment(array $params);
-//     abstract public function DoCapture(array $params);
-//     abstract public function DoAuthorization(array $params);
-//     abstract public function DoVoid(array $params);
-//     abstract public function DoDirectPayment(array $params);
-//     abstract public function RefundTransaction(array $params);
-//     abstract public function orderData(array $params);
-//     abstract public function getOrder(int $orderID);
-//     abstract public function authorizeOrder(int $orderID);
-//     abstract public function captureOrder(int $orderID);
 }
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
index 0247c27a..d8e89c20 100644
--- a/src/angelleye/PayPal/PayPalClassic.php
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -83,15 +83,6 @@ function __construct($DataArray)
             $this->Sandbox = true;
         }
 
-        // abstract public function SetExpressCheckout(array $params);
-        // abstract public function GetExpressCheckoutDetails($token);
-        // abstract public function DoExpressCheckoutPayment(array $params);
-        // abstract public function DoCapture(array $params);
-        // abstract public function DoAuthorization(array $params);
-        // abstract public function DoVoid(array $params);
-        // abstract public function DoDirectPayment(array $params);
-        // abstract public function RefundTransaction(array $params);
-
         $this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0';
         $this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature';
         $this->payPalAPIMode = isset($DataArray['payPalAPIMode']) ? $DataArray['payPalAPIMode'] : 'classic';
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 53b61cad..215f36ca 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -20,11 +20,6 @@ public function __construct($config)
         // Call parent constructor first
         parent::__construct($config);
 
-        // abstract public function orderData(array $params);
-        // abstract public function getOrder(int $orderID);
-        // abstract public function authorizeOrder(int $orderID);
-        // abstract public function captureOrder(int $orderID);
-
         // Override base URL for REST API endpoints
         $this->base_url = $this->Sandbox
             ? 'https://api-m.sandbox.paypal.com'

From 511947d7c6705b8ee9406859f00b5ff1cca46498 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Tue, 14 Oct 2025 18:10:29 +0530
Subject: [PATCH 011/146] GetBalance File Completion in REST Templates

---
 samples/rest/GetBalance.php         | 28 +++++++++++++++++
 src/angelleye/PayPal/PayPal.php     |  2 +-
 src/angelleye/PayPal/PayPalREST.php | 49 +++++++++++++++++++++++++++--
 templates/rest/GetBalance.php       | 28 +++++++++++++++++
 4 files changed, 103 insertions(+), 4 deletions(-)
 create mode 100644 samples/rest/GetBalance.php
 create mode 100644 templates/rest/GetBalance.php

diff --git a/samples/rest/GetBalance.php b/samples/rest/GetBalance.php
new file mode 100644
index 00000000..45f663cd
--- /dev/null
+++ b/samples/rest/GetBalance.php
@@ -0,0 +1,28 @@
+ $sandbox,
+		'PayPalAPIMode' => $api_mode,
+		'ClientID' => $rest_client_id,
+		'ClientSecret' => $rest_client_secret,
+		'PrintHeaders' => $print_headers,
+		'LogResults' => $log_results,
+		'LogPath' => $log_path,
+	);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$GBFields = array('returnallcurrencies' => '');
+$PayPalRequestData = array('GBFields'=>$GBFields);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetBalance($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPal.php b/src/angelleye/PayPal/PayPal.php
index c396dc42..2aefb18b 100755
--- a/src/angelleye/PayPal/PayPal.php
+++ b/src/angelleye/PayPal/PayPal.php
@@ -61,7 +61,7 @@ public function __construct(array $config = [])
      */
     public static function init(array $config = [])
     {
-        $apiMode = isset($config['api_mode']) ? $config['api_mode'] : 'classic';
+        $apiMode = isset($config['PayPalAPIMode']) ? $config['PayPalAPIMode'] : 'classic';
 
         switch (strtolower($apiMode)) {
             case 'rest':
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 215f36ca..4ad516fe 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -20,6 +20,8 @@ public function __construct($config)
         // Call parent constructor first
         parent::__construct($config);
 
+        $this->Sandbox = isset($config['Sandbox']) ? true : false;
+
         // Override base URL for REST API endpoints
         $this->base_url = $this->Sandbox
             ? 'https://api-m.sandbox.paypal.com'
@@ -90,8 +92,6 @@ private function getAccessToken()
             return $this->accessToken;
         }
 
-        $auth = base64_encode($this->client_id . ':' . $this->client_secret);
-
         $headers = $this->getOAuthHeaders();
         $postData = 'grant_type=client_credentials';
 
@@ -101,7 +101,7 @@ private function getAccessToken()
         curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
         $response = curl_exec($ch);
         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
@@ -150,6 +150,49 @@ protected function makeRequest($endpoint, $method = 'GET', $data = null)
         ];
     }
 
+    /**
+     * Obtain the available balance for a PayPal account.
+     *
+     * @access  public
+     * @return  mixed[] Returns an array structure of the PayPal HTTP response params as well as parsed balance results, errors and the raw request/response.
+     */
+    function GetBalance($DataArray)
+    {
+        $returnAllCurrencies = !empty($DataArray['GBFields']['returnallcurrencies']) ? true : false;
+
+        $response = $this->makeRequest('/v1/reporting/balances');
+
+        $responseSimplified = [
+            'ASOFTIME' => !empty($response['body']['as_of_time']) ? $response['body']['as_of_time'] : '',
+            'ACCOUNTID' => !empty($response['body']['account_id']) ? $response['body']['account_id'] : '',
+            'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+            'ERRORS' => [],
+            'BALANCES' => [],
+            'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : '',
+        ];
+
+        // Capture errors if available
+        if (!empty($response['body']['errors']) && is_array($response['body']['errors'])) {
+            $responseSimplified['errors'] = $response['body']['errors'];
+        }
+
+        if (!empty($response['body']['balances']) && is_array($response['body']['balances'])) {
+            foreach ($response['body']['balances'] as $balance) {
+                if ($returnAllCurrencies || !empty($balance['primary'])) {
+                    $responseSimplified['BALANCES'][] = [
+                        'CURRENCY' => !empty($balance['currency']) ? $balance['currency'] : '',
+                        'TOTALBALANCE' => !empty($balance['total_balance']['value']) ? $balance['total_balance']['value'] : 0,
+                        'AVAILABLEBALANCE' => !empty($balance['available_balance']['value']) ? $balance['available_balance']['value'] : 0,
+                        'WITHHELDBALANCE' => !empty($balance['withheld_balance']['value']) ? $balance['withheld_balance']['value'] : 0,
+                        'PRIMARY' => !empty($balance['primary']) ? 1 : 0,
+                    ];
+                }
+            }
+        }
+
+        return $responseSimplified;
+    }
+
     /**
      * Test OAuth authentication
      */
diff --git a/templates/rest/GetBalance.php b/templates/rest/GetBalance.php
new file mode 100644
index 00000000..cd673091
--- /dev/null
+++ b/templates/rest/GetBalance.php
@@ -0,0 +1,28 @@
+ $sandbox,
+		'PayPalAPIMode' => $api_mode,
+		'ClientID' => $rest_client_id,
+		'ClientSecret' => $rest_client_secret,
+		'PrintHeaders' => $print_headers,
+		'LogResults' => $log_results,
+		'LogPath' => $log_path,
+	);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$GBFields = array('returnallcurrencies' => true);
+$PayPalRequestData = array('GBFields'=>$GBFields);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetBalance($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 72135e1c1b3a6468c316c0f71d93f9341c1b6972 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 15 Oct 2025 10:54:30 +0530
Subject: [PATCH 012/146] GetBalance File Completion in REST Templates
 Remaining

---
 templates/classic/GetBalance.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/templates/classic/GetBalance.php b/templates/classic/GetBalance.php
index 2ca9af37..970ae8fa 100644
--- a/templates/classic/GetBalance.php
+++ b/templates/classic/GetBalance.php
@@ -14,7 +14,7 @@
 					'LogPath' => $log_path,
 					);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $GBFields = array('returnallcurrencies' => true);

From 1beed2a80f18d61da8dbc58f50c4a7070df71ef8 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 15 Oct 2025 18:45:31 +0530
Subject: [PATCH 013/146] Adaptive Method for AddBankAccount Work In Progress

---
 samples/classic/AddBankAccount.php     |  98 ++++++-------
 samples/classic/BMCreateButton.php     |   3 +-
 samples/rest/AddBankAccount.php        |  70 +++++++++
 samples/rest/BMCreateButton.php        | 187 +++++++++++++++++++++++++
 src/angelleye/PayPal/PayPal.php        |   2 +-
 src/angelleye/PayPal/PayPalClassic.php |   6 +
 templates/classic/AddBankAccount.php   |  98 ++++++-------
 templates/rest/AddBankAccount.php      |  71 ++++++++++
 8 files changed, 437 insertions(+), 98 deletions(-)
 create mode 100644 samples/rest/AddBankAccount.php
 create mode 100644 samples/rest/BMCreateButton.php
 create mode 100644 templates/rest/AddBankAccount.php

diff --git a/samples/classic/AddBankAccount.php b/samples/classic/AddBankAccount.php
index 886a5fb3..aa3e7ae1 100644
--- a/samples/classic/AddBankAccount.php
+++ b/samples/classic/AddBankAccount.php
@@ -5,64 +5,66 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => '',
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => '',
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $AddBankAccountFields = array(
-							'AccountHolderDateOfBirth' => '', 									// The date of birth of the account holder.  Format:  YYYY-MM-DDZ (ie. 1970-01-01Z)
-							'AccountID' => '', 													// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
-							'AgencyNumber' => '', 												// For the Brazil Agency Number
-							'BankAccountNumber' => '123456789', 											// The account number (BBAN) of the bank account to be added.
-							'BankAccountType' => 'CHECKING', 											// The type of bank account to be added.  Values are:  CHECKING, SAVINGS, BUSINESS_SAVINGS, BUSINESS_CHECKING, NORMAL, UNKNOWN
-							'BankCode' => '', 													// The code that identifies the bank where the account is held.
-							'BankCountryCode' => 'US', 											// Required.  The country code of the bank.
-							'BankName' => 'Bank of America', 													// The name of the bank.  
-							'BankTransitNumber' => '', 											// The transit number of the bank.
-							'BranchCode' => '', 												// The branch code for the bank.
-							'BranchLocation' => '', 											// The branch location.
-							'BSBNumber' => '', 													// The Bank/State/Branch number for the bank.
-							'CLABE' => '', 														// CLABE represents the bank information for countries like Mexico.
-							'ConfirmationType' => 'WEB', 											// Required.  Whether PayPal account holders are redirected to PayPal.com to confirm the bank account addition.  When you pass NONE for this param, the addition is made without the account holder's explicit confirmation.  If you pass WEB, a URL is returned.  Values are:  WEB, NONE.  NONE requires advanced permissions.
-							'ControlDigit' => '', 												// The control digits for the bank.
-							'EmailAddress' => 'sandbo_1204199080_biz@angelleye.com', 												// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
-							'IBAN' => '', 														// The IBAN for the bank.
-							'InstitutionNumber' => '', 											// The institution number for the bank.
-							'PartnerInfo' => '', 												// The partner information for the bank.
-							'RibKey' => '', 													// The RIB Key for the bank
-							'RoutingNumber' => '101000010', 												// The bank's routing number.
-							'SortCode' => '', 													// The branch sort code.
-							'TaxIDType' => '', 													// Tax ID type of CNPJ or CPF, only supported for Brazil
-							'TaxIDNumber' => '' 												// Tax ID number for Brazil
-							);
+	'AccountHolderDateOfBirth' => '', 				// The date of birth of the account holder.  Format:  YYYY-MM-DDZ (ie. 1970-01-01Z)
+	'AccountID' => '', 						// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
+	'AgencyNumber' => '', 						// For the Brazil Agency Number
+	'BankAccountNumber' => '123456789', 				// The account number (BBAN) of the bank account to be added.
+	'BankAccountType' => 'CHECKING', 				// The type of bank account to be added.  Values are:  CHECKING, SAVINGS, BUSINESS_SAVINGS, BUSINESS_CHECKING, NORMAL, UNKNOWN
+	'BankCode' => '', 						// The code that identifies the bank where the account is held.
+	'BankCountryCode' => 'US', 					// Required.  The country code of the bank.
+	'BankName' => 'Bank of America', 				// The name of the bank.  
+	'BankTransitNumber' => '', 					// The transit number of the bank.
+	'BranchCode' => '', 						// The branch code for the bank.
+	'BranchLocation' => '', 					// The branch location.
+	'BSBNumber' => '', 						// The Bank/State/Branch number for the bank.
+	'CLABE' => '', 							// CLABE represents the bank information for countries like Mexico.
+	'ConfirmationType' => 'WEB', 					// Required.  Whether PayPal account holders are redirected to PayPal.com to confirm the bank account addition.  When you pass NONE for this param, the addition is made without the account holder's explicit confirmation.  If you pass WEB, a URL is returned.  Values are:  WEB, NONE.  NONE requires advanced permissions.
+	'ControlDigit' => '', 						// The control digits for the bank.
+	'EmailAddress' => 'sandbo_1204199080_biz@angelleye.com', 	// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
+	'IBAN' => '', 							// The IBAN for the bank.
+	'InstitutionNumber' => '', 					// The institution number for the bank.
+	'PartnerInfo' => '', 						// The partner information for the bank.
+	'RibKey' => '', 						// The RIB Key for the bank
+	'RoutingNumber' => '101000010', 				// The bank's routing number.
+	'SortCode' => '', 						// The branch sort code.
+	'TaxIDType' => '', 						// Tax ID type of CNPJ or CPF, only supported for Brazil
+	'TaxIDNumber' => '' 						// Tax ID number for Brazil
+);
 							
 $WebOptions = array(
-					'CancelURL' => $domain.'cancel.php', 															// The URL to which the user is returned when they cancel the flow at PayPal.com
-					'CancelURLDescription' => 'This is where you go if you cancel the process.', 												// A description for the CancelURL
-					'ReturnURL' => $domain.'return.php', 															// The URL to which the user is returned when they complete the process.
-					'ReturnURLDescription' => 'This is where you go if you complete the process.'												// A description for the ReturnURL
-					);
+	'CancelURL' => $domain.'cancel.php', 							// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => 'This is where you go if you cancel the process.', 		// A description for the CancelURL
+	'ReturnURL' => $domain.'return.php', 							// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => 'This is where you go if you complete the process.'		// A description for the ReturnURL
+);
 
 $PayPalRequestData = array(
-						   'AddBankAccountFields' => $AddBankAccountFields, 
-						   'WebOptions' => $WebOptions
-						   );
+	'AddBankAccountFields' => $AddBankAccountFields, 
+	'WebOptions' => $WebOptions
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->AddBankAccount($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->AddBankAccount($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/BMCreateButton.php b/samples/classic/BMCreateButton.php
index 611dfb09..fe32bf6a 100644
--- a/samples/classic/BMCreateButton.php
+++ b/samples/classic/BMCreateButton.php
@@ -6,6 +6,7 @@
 // Create PayPal object.
 $PayPalConfig = array(
 					'Sandbox' => $sandbox,
+                    'PayPalAPIMode' => $api_mode,
 					'APIUsername' => $api_username,
 					'APIPassword' => $api_password,
 					'APISignature' => $api_signature, 
@@ -14,7 +15,7 @@
 					'LogPath' => $log_path,
 					);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $BMCreateButtonFields = array
diff --git a/samples/rest/AddBankAccount.php b/samples/rest/AddBankAccount.php
new file mode 100644
index 00000000..f778d46d
--- /dev/null
+++ b/samples/rest/AddBankAccount.php
@@ -0,0 +1,70 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => '',
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$AddBankAccountFields = array(
+	'AccountHolderDateOfBirth' => '', 				// The date of birth of the account holder.  Format:  YYYY-MM-DDZ (ie. 1970-01-01Z)
+	'AccountID' => '', 						// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
+	'AgencyNumber' => '', 						// For the Brazil Agency Number
+	'BankAccountNumber' => '123456789', 				// The account number (BBAN) of the bank account to be added.
+	'BankAccountType' => 'CHECKING', 				// The type of bank account to be added.  Values are:  CHECKING, SAVINGS, BUSINESS_SAVINGS, BUSINESS_CHECKING, NORMAL, UNKNOWN
+	'BankCode' => '', 						// The code that identifies the bank where the account is held.
+	'BankCountryCode' => 'US', 					// Required.  The country code of the bank.
+	'BankName' => 'Bank of America', 				// The name of the bank.  
+	'BankTransitNumber' => '', 					// The transit number of the bank.
+	'BranchCode' => '', 						// The branch code for the bank.
+	'BranchLocation' => '', 					// The branch location.
+	'BSBNumber' => '', 						// The Bank/State/Branch number for the bank.
+	'CLABE' => '', 							// CLABE represents the bank information for countries like Mexico.
+	'ConfirmationType' => 'WEB', 					// Required.  Whether PayPal account holders are redirected to PayPal.com to confirm the bank account addition.  When you pass NONE for this param, the addition is made without the account holder's explicit confirmation.  If you pass WEB, a URL is returned.  Values are:  WEB, NONE.  NONE requires advanced permissions.
+	'ControlDigit' => '', 						// The control digits for the bank.
+	'EmailAddress' => 'sandbo_1204199080_biz@angelleye.com', 	// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
+	'IBAN' => '', 							// The IBAN for the bank.
+	'InstitutionNumber' => '', 					// The institution number for the bank.
+	'PartnerInfo' => '', 						// The partner information for the bank.
+	'RibKey' => '', 						// The RIB Key for the bank
+	'RoutingNumber' => '101000010', 				// The bank's routing number.
+	'SortCode' => '', 						// The branch sort code.
+	'TaxIDType' => '', 						// Tax ID type of CNPJ or CPF, only supported for Brazil
+	'TaxIDNumber' => '' 						// Tax ID number for Brazil
+);
+							
+$WebOptions = array(
+	'CancelURL' => $domain.'cancel.php', 							// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => 'This is where you go if you cancel the process.', 		// A description for the CancelURL
+	'ReturnURL' => $domain.'return.php', 							// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => 'This is where you go if you complete the process.'		// A description for the ReturnURL
+);
+
+$PayPalRequestData = array(
+	'AddBankAccountFields' => $AddBankAccountFields, 
+	'WebOptions' => $WebOptions
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->Adaptive->AddBankAccount($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/samples/rest/BMCreateButton.php b/samples/rest/BMCreateButton.php
new file mode 100644
index 00000000..f5cfd797
--- /dev/null
+++ b/samples/rest/BMCreateButton.php
@@ -0,0 +1,187 @@
+ $sandbox,
+    'PayPalAPIMode' => $api_mode,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret,
+    'PrintHeaders' => $print_headers, 
+    'LogResults' => $log_results,
+    'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$BMCreateButtonFields = array(
+    'buttoncode' => 'CLEARTEXT', 	// The kind of button code to create.  It is one of the following values:  HOSTED, ENCRYPTED, CLEARTEXT, TOKEN
+    'buttontype' => 'CART',			// Required.  The kind of button you want to create.  It is one of the following values:  BUYNOW, CART, GIFTCERTIFICATE, SUBSCRIBE, DONATE, UNSUBSCRIBE, VIEWCART, PAYMENTPLAN, AUTOBILLING, PAYMENT
+    'buttonsubtype' => '',          // The use of button you want to create.  Values are:  PRODUCTS, SERVICES
+);
+
+/**
+ * You may pass in any variables from the Standard Payments list.
+ *
+ * Depending on the type of button you are creating some variables will be required.
+ * Refer to the HTML Standard Variable reference for more details on variables for specific button types.
+ *
+ * https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
+ */
+$BMButtonVars = array(
+    'notify_url' => '',                         // The URL to which PayPal posts information about the payment. in the form of an IPN message.
+    'amount' => '',                             // The price or amount of the product, service, or contribution, not including shipping, handling, or tax.  If this variable is omitted from Buy Now or Donate buttons, buyers enter their own amount at the time of the payment.
+    'discount_amount' => '',                    // Discount amount associated with an item.  Must be less than the selling price of the item.  Valid only for Buy Now and Add to Cart buttons.
+    'discount_amount2' => '',                   // Discount amount associated with each additional quantity of the item.  Must be equal to or less than the selling price of the item.
+    'discount_rate' => '',                      // Discount rate (percentage) associated with an item.  Must be set to a value less than 100.
+    'discount_rate2' => '',                     // Discount rate (percentage) associated with each additional quantity of the item.  Must be equal to or less than 100.
+    'discount_num' => '',                       // Number of additional quantities of the item to which the discount applies.
+    'item_name' => 'Test Widget',               // Description of the item.  If this is omitted, buyers enter their own name during checkout.
+    'item_number' => '',                        // Pass-through variable for you to track product or service purchased or the contribution made.
+    'quantity' => '',                           // Number of items.
+    'shipping' => '',                           // The cost of shipping this item.
+    'shipping2' => '',                          // The cost of shipping each additional unit of this item.
+    'handling' => '',                           // handling charges.  This variable is not quantity-specific.
+    'tax' => '',                                // Transaction-based tax override variable.  Set this variable to a flat tax amount to apply to the payment regardless of the buyer's location.  This overrides any tax settings in the account profile.
+    'tax_rate' => '',                           // Transaction-based tax override variable.  Set this variable to a percentage that applies to the amount multipled by the quantity selected uring checkout.  This overrides your paypal account profile.
+    'undefined_quantity' =>'',                  // Set to 1 to allow the buyer to specify the quantity.
+    'weight' => '',                             // Weight of items.
+    'weight_unit' => '',                        // The unit of measure if weight is specified.  Values are:  lbs, kgs
+    'address_override' => '',                   // Set to 1 to override the payer's address stored in their PayPal account.
+    'currency_code' => '',                      // The currency of the payment.  https://developer.paypal.com/docs/classic/api/currency_codes/#id09A6G0U0GYK
+    'custom' => '',                             // Pass-through variable for your own tracking purposes, which buyers do not see.
+    'invoice' => '',                            // Pass-through variable you can use to identify your invoice number for the purchase.
+    'tax_cart' => '',                           // Cart-wide tax, overriding any individual item tax_ value
+    'handling_cart' => '',                      // Single handling fee charged cart-wide.
+    'weight_cart' => '',                        // If profile-based shipping rates are configured with a basis of weight, PayPal uses this value to calculate the shipping charges for the payment.  This value overrides the weight values of individual items.
+    'add' => '',                                // Set to 1 to add an item to the PayPal shopping cart.
+    'display' => '',                            // Set to 1 to display the contents of the PayPal shopping cart to the buyer.
+    'upload' => '',                             // Set to 1 to upload the contents of a third-party shopping cart or a custom shopping cart.
+    'business' => 'sandbo_1215254764_biz@angelleye.com',                           // Your PayPal ID or an email address associated with your PayPal account.  Email addresses must be confirmed.
+    'paymentaction' => '',                      // Indicates whether the payment is a finale sale or an authorization for a final sale, to be captured later.  Values are:  sale, authorization, order
+    'shopping_url' => '',                       // The URL of the page on the merchant website that buyers go to when they click the Continue Shopping button on the PayPal shopping cart page.
+    'a1' => '',                                 // Trial period 1 price.  For a free trial period, specify 0.
+    'p1' => '',                                 // Trial period 1 duration.  Required if you specify a1.
+    't1' => '',                                 // Trial period 1 units of duration.  Values are:  D, W, M, Y
+    'a2' => '',                                 // Trial period 2 price.  Can be specified only if you also specify a1.
+    'p2' => '',                                 // Trial period 2 duration.
+    't2' => '',                                 // Trial period 2 units of duration.
+    'a3' => '',                                 // Regular subscription price.
+    'p3' => '',                                 // Regular subscription duration.
+    't3' => '',                                 // Regular subscription units of duration.
+    'src' => '',                                // Recurring payments.  Subscription payments recur unless subscribers cancel.  Values are:  1, 0
+    'sra' => '',                                // Reattempt on failure.  If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling.  Values are:  1, 0
+    'no_note' => '',                            // Set to 1 to disable prompts for buyers to include a note with their payments.
+    'modify' => '',                             // Modification behavior.  0 - allows subscribers only to sign up for new subscriptions.  1 - allows subscribers to sign up for new subscriptions and modify their current subscriptions.  2 - allows subscribers to modify only their current subscriptions.
+    'usr_manage' => '',                         // Set to 1 to have PayPal generate usernames and passwords for subscribers.  https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscribe_buttons/#id08ADFB00QWS
+    'max_text' => '',                           // A description of the automatic billing plan.
+    'set_customer_limit' => '',                 // Specify whether to let buyers enter maximum billing limits in a text box or choose from a list of max billing limits that you specify.  Values are:  max_limit_own, max_limit_defined
+    'min_amount' => '',                         // The minimum monthly billing limit, if you have one.
+    'disp_tot' => '',                           // Display the total payment amount to buyers during checkout.  Values are:  Y, N
+    'page_style' => '',                         // The custom payment page style for checkout pages.  Values are:  paypal, primary, page_style_name
+    'image_url' => '',                          // The URL of the 150x50 image displayed as your logo on the PayPal checkout pages.
+    'cpp_cart_border_color' => '',              // The HTML hex code for your principal identifying color.  PayPal blends your color to white on the checkout pages.
+    'cpp_header_image' => '',                   // The image at the top, left of the checkout page.  Max size is 750x90.
+    'cpp_headerback_color' => '',               // The background color for the header of the checkout page.
+    'cpp_headerborder_color' => '',             // The border color around the header of the checkout page.
+    'cpp_logo_image' => '',                     // A URL to your logo image.  Must be .gif, .jpg, or .png.  190x60
+    'cpp_payflow_color' => '',                  // The background color for the checkout page below the header.
+    'lc' => '',                                 // The locale of the login or sign-up page.
+    'cn' => '',                                 // Label that appears above the note field.
+    'no_shipping' => '',                        // Do not prompt buyers for a shipping address.  Values are:  0 - prompt for an address but do not require.  1 - do not prompt.  2 - prompt and require address.
+    'return' => '',                             // The URL to which PayPal redirects buyers' browsers after they complete their payment.
+    'rm' => '',                                 // Return method.  Values are:  0 - all shopping cart payments use GET method.  1 - buyer's browser is redirected using the GET method. 2 - buyer's browser is redirected using POST.
+    'cbt' => '',                                // Sets the text for the Return to Merchant button on the PayPal completed payment page.
+    'cancel_return' => '',                      // A URL to which PayPal redirects buyers if they cancel the payment.
+    'address1' => '',
+    'address2' => '',
+    'city' => '',
+    'state' => '',
+    'zip' => '',
+    'country' => '',
+    'email' => '',
+    'first_name' => '',
+    'last_name' => '',
+    'charset' => '',                            // Sets the character set and character encoding for the billing login page.
+    'night_phone_a' => '',                      // Area code for US phone numbers or country code for phone numbers outside the US.
+    'night_phone_b' => '',                      // 3 digit prefix for US numbers or the entire phone number for numbers outside the US.
+    'night_phone_c' => '',                      // 4 digit phone number for US numbers.
+);
+
+/**
+ * Button options are handled similar to order items in other calls within this library.
+ * You will need to setup a nested array of options and option selections.
+ *
+ * You could end up with multiple $BMButtonOption arrays here, and each of those could
+ * contain multiple $BMButtonOptionSelection arrays within it.  All are then passed into
+ * the final $BMButtonOptions array that gets passed to the API.
+ *
+ * This sample includes 2 options.  The Color option, which contains 3 selections (with pricing),
+ * and the Size option, which contains 2 selections (without pricing).
+ */
+$BMButtonOptions = array();
+
+$BMButtonOptionSelections = array();
+$BMButtonOptionSelection = array(
+    'value' => 'Blue',
+    'price' => '10.00',
+    'type' => ''
+);
+array_push($BMButtonOptionSelections, $BMButtonOptionSelection);
+
+$BMButtonOptionSelection = array(
+    'value' => 'Red',
+    'price' => '8.00',
+    'type' => ''
+);
+array_push($BMButtonOptionSelections, $BMButtonOptionSelection);
+
+$BMButtonOptionSelection = array(
+    'value' => 'Green',
+    'price' => '12.00',
+    'type' => ''
+);
+array_push($BMButtonOptionSelections, $BMButtonOptionSelection);
+
+$BMButtonOption = array(
+    'name' => 'Color',
+    'selections' => $BMButtonOptionSelections
+);
+array_push($BMButtonOptions, $BMButtonOption);
+
+
+$BMButtonOptionSelections = array();
+$BMButtonOptionSelection = array(
+    'value' => 'Small',
+    'price' => '',
+    'type' => ''
+);
+array_push($BMButtonOptionSelections, $BMButtonOptionSelection);
+
+$BMButtonOptionSelection = array(
+    'value' => 'Large',
+    'price' => '',
+    'type' => ''
+);
+array_push($BMButtonOptionSelections, $BMButtonOptionSelection);
+
+$BMButtonOption = array(
+    'name' => 'Size',
+    'selections' => $BMButtonOptionSelections
+);
+array_push($BMButtonOptions, $BMButtonOption);
+
+$PayPalRequestData = array(
+    'BMCreateButtonFields' => $BMCreateButtonFields,
+    'BMButtonVars' => $BMButtonVars,
+    'BMButtonOptions' => $BMButtonOptions
+);
+
+$PayPalResult = $PayPal->BMCreateButton($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPal.php b/src/angelleye/PayPal/PayPal.php
index 2aefb18b..a24bb77a 100755
--- a/src/angelleye/PayPal/PayPal.php
+++ b/src/angelleye/PayPal/PayPal.php
@@ -49,7 +49,7 @@ class PayPal
 
     public function __construct(array $config = [])
     {
-	$this->config = $config;
+	    $this->config = $config;
         $this->mode = isset($config['Sandbox']) ? $config['Sandbox'] : 'live';
         $this->payPalAPIMode = isset($config['PayPalAPIMode']) ? $config['PayPalAPIMode'] : 'classic';
         $this->Sandbox = ($this->mode === 'sandbox') ? true : false;
diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
index d8e89c20..24c3c0fd 100644
--- a/src/angelleye/PayPal/PayPalClassic.php
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -68,6 +68,8 @@ class PayPalClassic extends PayPal
     protected array $AVSCodes;
     protected array $CVV2Codes;
     protected array $CurrencyCodes;
+
+    public Adaptive $Adaptive;
 /**
      * Constructor
      *
@@ -83,6 +85,10 @@ function __construct($DataArray)
             $this->Sandbox = true;
         }
 
+        if (isset($DataArray['isAdaptive'])) {
+            $this->Adaptive = new Adaptive($DataArray);
+        }
+
         $this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0';
         $this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature';
         $this->payPalAPIMode = isset($DataArray['payPalAPIMode']) ? $DataArray['payPalAPIMode'] : 'classic';
diff --git a/templates/classic/AddBankAccount.php b/templates/classic/AddBankAccount.php
index 9faaf0ba..b197663e 100644
--- a/templates/classic/AddBankAccount.php
+++ b/templates/classic/AddBankAccount.php
@@ -6,64 +6,66 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $AddBankAccountFields = array(
-							'AccountHolderDateOfBirth' => '', 									// The date of birth of the account holder.  Format:  YYYY-MM-DDZ (ie. 1970-01-01Z)
-							'AccountID' => '', 													// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
-							'AgencyNumber' => '', 												// For the Brazil Agency Number
-							'BankAccountNumber' => '', 											// The account number (BBAN) of the bank account to be added.
-							'BankAccountType' => '', 											// The type of bank account to be added.  Values are:  CHECKING, SAVINGS, BUSINESS_SAVINGS, BUSINESS_CHECKING, NORMAL, UNKNOWN
-							'BankCode' => '', 													// The code that identifies the bank where the account is held.
-							'BankCountryCode' => '', 											// Required.  The country code of the bank.
-							'BankName' => '', 													// The name of the bank.  
-							'BankTransitNumber' => '', 											// The transit number of the bank.
-							'BranchCode' => '', 												// The branch code for the bank.
-							'BranchLocation' => '', 											// The branch location.
-							'BSBNumber' => '', 													// The Bank/State/Branch number for the bank.
-							'CLABE' => '', 														// CLABE represents the bank information for countries like Mexico.
-							'ConfirmationType' => '', 											// Required.  Whether PayPal account holders are redirected to PayPal.com to confirm the bank account addition.  When you pass NONE for this param, the addition is made without the account holder's explicit confirmation.  If you pass WEB, a URL is returned.  Values are:  WEB, NONE.  NONE requires advanced permissions.
-							'ControlDigit' => '', 												// The control digits for the bank.
-							'EmailAddress' => '', 												// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
-							'IBAN' => '', 														// The IBAN for the bank.
-							'InstitutionNumber' => '', 											// The institution number for the bank.
-							'PartnerInfo' => '', 												// The partner information for the bank.
-							'RibKey' => '', 													// The RIB Key for the bank
-							'RoutingNumber' => '', 												// The bank's routing number.
-							'SortCode' => '', 													// The branch sort code.
-							'TaxIDType' => '', 													// Tax ID type of CNPJ or CPF, only supported for Brazil
-							'TaxIDNumber' => '' 												// Tax ID number for Brazil
-							);
+	'AccountHolderDateOfBirth' => '', 	// The date of birth of the account holder.  Format:  YYYY-MM-DDZ (ie. 1970-01-01Z)
+	'AccountID' => '', 			// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
+	'AgencyNumber' => '', 			// For the Brazil Agency Number
+	'BankAccountNumber' => '', 		// The account number (BBAN) of the bank account to be added.
+	'BankAccountType' => '', 		// The type of bank account to be added.  Values are:  CHECKING, SAVINGS, BUSINESS_SAVINGS, BUSINESS_CHECKING, NORMAL, UNKNOWN
+	'BankCode' => '', 			// The code that identifies the bank where the account is held.
+	'BankCountryCode' => '', 		// Required.  The country code of the bank.
+	'BankName' => '', 			// The name of the bank.  
+	'BankTransitNumber' => '', 		// The transit number of the bank.
+	'BranchCode' => '', 			// The branch code for the bank.
+	'BranchLocation' => '', 		// The branch location.
+	'BSBNumber' => '', 			// The Bank/State/Branch number for the bank.
+	'CLABE' => '', 				// CLABE represents the bank information for countries like Mexico.
+	'ConfirmationType' => '', 		// Required.  Whether PayPal account holders are redirected to PayPal.com to confirm the bank account addition.  When you pass NONE for this param, the addition is made without the account holder's explicit confirmation.  If you pass WEB, a URL is returned.  Values are:  WEB, NONE.  NONE requires advanced permissions.
+	'ControlDigit' => '', 			// The control digits for the bank.
+	'EmailAddress' => '', 			// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
+	'IBAN' => '', 				// The IBAN for the bank.
+	'InstitutionNumber' => '', 		// The institution number for the bank.
+	'PartnerInfo' => '', 			// The partner information for the bank.
+	'RibKey' => '', 			// The RIB Key for the bank
+	'RoutingNumber' => '', 			// The bank's routing number.
+	'SortCode' => '', 			// The branch sort code.
+	'TaxIDType' => '', 			// Tax ID type of CNPJ or CPF, only supported for Brazil
+	'TaxIDNumber' => '' 			// Tax ID number for Brazil
+);
 							
 $WebOptions = array(
-					'CancelURL' => '', 															// The URL to which the user is returned when they cancel the flow at PayPal.com
-					'CancelURLDescription' => '', 												// A description for the CancelURL
-					'ReturnURL' => '', 															// The URL to which the user is returned when they complete the process.
-					'ReturnURLDescription' => ''												// A description for the ReturnURL
-					);
+	'CancelURL' => '', 			// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => '', 		// A description for the CancelURL
+	'ReturnURL' => '', 			// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => ''		// A description for the ReturnURL
+);
 
 $PayPalRequestData = array(
-						   'AddBankAccountFields' => $AddBankAccountFields, 
-						   'WebOptions' => $WebOptions
-						   );
+	'AddBankAccountFields' => $AddBankAccountFields, 
+	'WebOptions' => $WebOptions
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->AddBankAccount($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->AddBankAccount($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/AddBankAccount.php b/templates/rest/AddBankAccount.php
new file mode 100644
index 00000000..c7807ee2
--- /dev/null
+++ b/templates/rest/AddBankAccount.php
@@ -0,0 +1,71 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$AddBankAccountFields = array(
+	'AccountHolderDateOfBirth' => '', 	// The date of birth of the account holder.  Format:  YYYY-MM-DDZ (ie. 1970-01-01Z)
+	'AccountID' => '', 			// The ID number of the PayPal account for which a bank account is added.  You must specify either AccountID or EmailAddress for this request.
+	'AgencyNumber' => '', 			// For the Brazil Agency Number
+	'BankAccountNumber' => '', 		// The account number (BBAN) of the bank account to be added.
+	'BankAccountType' => '', 		// The type of bank account to be added.  Values are:  CHECKING, SAVINGS, BUSINESS_SAVINGS, BUSINESS_CHECKING, NORMAL, UNKNOWN
+	'BankCode' => '', 			// The code that identifies the bank where the account is held.
+	'BankCountryCode' => '', 		// Required.  The country code of the bank.
+	'BankName' => '', 			// The name of the bank.  
+	'BankTransitNumber' => '', 		// The transit number of the bank.
+	'BranchCode' => '', 			// The branch code for the bank.
+	'BranchLocation' => '', 		// The branch location.
+	'BSBNumber' => '', 			// The Bank/State/Branch number for the bank.
+	'CLABE' => '', 				// CLABE represents the bank information for countries like Mexico.
+	'ConfirmationType' => '', 		// Required.  Whether PayPal account holders are redirected to PayPal.com to confirm the bank account addition.  When you pass NONE for this param, the addition is made without the account holder's explicit confirmation.  If you pass WEB, a URL is returned.  Values are:  WEB, NONE.  NONE requires advanced permissions.
+	'ControlDigit' => '', 			// The control digits for the bank.
+	'EmailAddress' => '', 			// The email address of the PayPal account holder.  You must specify either AccountID or EmailAddress.
+	'IBAN' => '', 				// The IBAN for the bank.
+	'InstitutionNumber' => '', 		// The institution number for the bank.
+	'PartnerInfo' => '', 			// The partner information for the bank.
+	'RibKey' => '', 			// The RIB Key for the bank
+	'RoutingNumber' => '', 			// The bank's routing number.
+	'SortCode' => '', 			// The branch sort code.
+	'TaxIDType' => '', 			// Tax ID type of CNPJ or CPF, only supported for Brazil
+	'TaxIDNumber' => '' 			// Tax ID number for Brazil
+);
+							
+$WebOptions = array(
+	'CancelURL' => '', 			// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => '', 		// A description for the CancelURL
+	'ReturnURL' => '', 			// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => ''		// A description for the ReturnURL
+);
+
+$PayPalRequestData = array(
+	'AddBankAccountFields' => $AddBankAccountFields, 
+	'WebOptions' => $WebOptions
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->Adaptive->AddBankAccount($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 9e904d000cfbc41a19ce9ba34de4532b58557500 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Thu, 16 Oct 2025 18:52:03 +0530
Subject: [PATCH 014/146] Continue in Banking Common Methods

---
 samples/classic/AddPaymentCard.php       | 111 +++++++--------
 samples/classic/BMButtonSearch.php       |  28 ++--
 samples/classic/BMCreateButton.php       | 163 +++++++++++------------
 samples/classic/BMGetButtonDetails.php   |  19 +--
 samples/rest/AddBankAccount.php          |   2 +-
 samples/rest/AddPaymentCard.php          |  81 +++++++++++
 samples/rest/BMButtonSearch.php          |  32 +++++
 samples/rest/BMCreateButton.php          | 136 +++++++++----------
 samples/rest/BMGetButtonDetails.php      |  24 ++++
 src/angelleye/PayPal/PayPalREST.php      | 117 +++++++++++++++-
 templates/classic/AddPaymentCard.php     | 111 +++++++--------
 templates/classic/BMButtonSearch.php     |  26 ++--
 templates/classic/BMCreateButton.php     |  28 ++--
 templates/classic/BMGetButtonDetails.php |  19 +--
 templates/rest/AddBankAccount.php        |   2 +-
 templates/rest/AddPaymentCard.php        |  81 +++++++++++
 templates/rest/BMButtonSearch.php        |  32 +++++
 templates/rest/BMCreateButton.php        | 154 +++++++++++++++++++++
 templates/rest/BMGetButtonDetails.php    |  24 ++++
 19 files changed, 864 insertions(+), 326 deletions(-)
 create mode 100644 samples/rest/AddPaymentCard.php
 create mode 100644 samples/rest/BMButtonSearch.php
 create mode 100644 samples/rest/BMGetButtonDetails.php
 create mode 100644 templates/rest/AddPaymentCard.php
 create mode 100644 templates/rest/BMButtonSearch.php
 create mode 100644 templates/rest/BMCreateButton.php
 create mode 100644 templates/rest/BMGetButtonDetails.php

diff --git a/samples/classic/AddPaymentCard.php b/samples/classic/AddPaymentCard.php
index 1849355b..23f39d10 100644
--- a/samples/classic/AddPaymentCard.php
+++ b/samples/classic/AddPaymentCard.php
@@ -3,78 +3,79 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => '',
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => '',
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'isAdaptive' => true,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
-$AddPaymentCardFields = array(
-								'AccountID' => '', 												// The ID number of the PayPal account for which the payment card is being added.  You must specify either AccountID or EmailAdddress
-								'CardNumber' => '5581588041402157', 											// Required.  The credit card number.
-								'CardOwnerDateOfBirth' => '', 									// The date of birth of the card holder.
-								'CardType' => 'MasterCard', 												// Required.  The type of card being added.  Values are:  Visa, MasterCard, AmericanExpress, Discover, SwitchMaestro, Solo, CarteAurore, CarteBleue, Cofinoga, 4etoiles, CarteAura, TarjetaAurora, JCB
-								'CardVerificationNumber' => '', 								// The verification code for the card.  Generally required for calls where ConfirmationType is set to NONE.  With the appropriate account review, this param is optional.
-								'ConfirmationType' => 'WEB', 										// Required.  Whether the account holder is redirected to PayPal.com to confirm the card addition.  Values are:  WEB, NONE
-								'CreateAccountKey' => '', 										// The key returned in a CreateAccount response.  Required for calls where the ConfirmationType is NONE.
-								'EmailAddress' => 'sandbo_1204199080_biz@angelleye.com', 											// Email address of the account holder adding the card.  Must specify either AccountID or EmailAddress.
-								'IssueNumber' => '', 											// The 2-digit issue number for Switch, Maestro, and Solo cards.
-								'StartDate' => '' 												// The element containing the start date for the payment card.
-							);
+$AddPaymentCardFields = array(		
+	'AccountID' => '', 						// The ID number of the PayPal account for which the payment card is being added.  You must specify either AccountID or EmailAdddress
+	'CardNumber' => '5581588041402157', 				// Required.  The credit card number.
+	'CardOwnerDateOfBirth' => '', 					// The date of birth of the card holder.
+	'CardType' => 'MasterCard', 					// Required.  The type of card being added.  Values are:  Visa, MasterCard, AmericanExpress, Discover, SwitchMaestro, Solo, CarteAurore, CarteBleue, Cofinoga, 4etoiles, CarteAura, TarjetaAurora, JCB
+	'CardVerificationNumber' => '', 				// The verification code for the card.  Generally required for calls where ConfirmationType is set to NONE.  With the appropriate account review, this param is optional.
+	'ConfirmationType' => 'WEB', 					// Required.  Whether the account holder is redirected to PayPal.com to confirm the card addition.  Values are:  WEB, NONE
+	'CreateAccountKey' => '', 					// The key returned in a CreateAccount response.  Required for calls where the ConfirmationType is NONE.
+	'EmailAddress' => 'sandbo_1204199080_biz@angelleye.com', 	// Email address of the account holder adding the card.  Must specify either AccountID or EmailAddress.
+	'IssueNumber' => '', 						// The 2-digit issue number for Switch, Maestro, and Solo cards.
+	'StartDate' => '' 						// The element containing the start date for the payment card.
+);
 							
 $NameOnCard = array(
-					'Salutation' => '', 														// A salutation for the card owner.
-					'FirstName' => 'Tester', 															// Required.  First name of the card holder.
-					'MiddleName' => '', 														// Middle name of the card holder.
-					'LastName' => 'Testerson', 															// Required.  Last name of the card holder.
-					'Suffix' => ''																// A suffix for the card holder.
-					);
+	'Salutation' => '', 		// A salutation for the card owner.
+	'FirstName' => 'Tester', 	// Required.  First name of the card holder.
+	'MiddleName' => '', 		// Middle name of the card holder.
+	'LastName' => 'Testerson', 	// Required.  Last name of the card holder.
+	'Suffix' => ''			// A suffix for the card holder.
+);
 							
 $BillingAddress = array(
-						'Line1' => '123 Test Ave.', 															// Required.  Billing street address.
-						'Line2' => '', 															// Billing street address 2
-						'City' => 'Grandview', 															// Required.  Billing city.
-						'State' => 'MO', 															// Billing state.
-						'PostalCode' => '64030',														// Billing postal code
-						'CountryCode' => 'US'														// Required.  Billing country code.
-						);
+	'Line1' => '123 Test Ave.', 	// Required.  Billing street address.
+	'Line2' => '', 			// Billing street address 2
+	'City' => 'Grandview', 		// Required.  Billing city.
+	'State' => 'MO', 		// Billing state.
+	'PostalCode' => '64030',	// Billing postal code
+	'CountryCode' => 'US'		// Required.  Billing country code.
+);
 
 $ExpirationDate = array(
-						'Month' => '12', 															// Expiration month.
-						'Year' => '2015'															// Required.  Expiration Year.
-						);
+	'Month' => '12', 		// Expiration month.
+	'Year' => '2015'		// Required.  Expiration Year.
+);
 							
 $WebOptions = array(
-					'CancelURL' => $domain.'cancel.php', 															// The URL to which the user is returned when they cancel the flow at PayPal.com
-					'CancelURLDescription' => 'Cancel and return to website.', 												// A description for the CancelURL
-					'ReturnURL' => $domain.'return.php', 															// The URL to which the user is returned when they complete the process.
-					'ReturnURLDescription' => 'Return to website.'												// A description for the ReturnURL
-					);
+	'CancelURL' => $domain.'cancel.php', 				// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => 'Cancel and return to website.', 	// A description for the CancelURL
+	'ReturnURL' => $domain.'return.php', 				// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => 'Return to website.'			// A description for the ReturnURL
+);
 
 $PayPalRequestData = array(
-						   'AddPaymentCardFields' => $AddPaymentCardFields, 
-						   'NameOnCard' => $NameOnCard, 
-						   'BillingAddress' => $BillingAddress, 
-						   'ExpirationDate' => $ExpirationDate, 
-						   'WebOptions' => $WebOptions
-						   );
+	'AddPaymentCardFields' => $AddPaymentCardFields, 
+	'NameOnCard' => $NameOnCard, 
+	'BillingAddress' => $BillingAddress, 
+	'ExpirationDate' => $ExpirationDate, 
+	'WebOptions' => $WebOptions
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->AddPaymentCard($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->AddPaymentCard($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/BMButtonSearch.php b/samples/classic/BMButtonSearch.php
index c486e1a4..623f08a0 100644
--- a/samples/classic/BMButtonSearch.php
+++ b/samples/classic/BMButtonSearch.php
@@ -5,23 +5,23 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
-$BMButtonSearchFields = array
-						(
-						'startdate' => '2009-01-01T00:00:00Z', 			// Required.  Starting date for the search.  UTC/GMT format: 2009-08-24T05:38:48Z
-						'enddate' => ''				// Ending date for the search.  UTC/GMT format: 2010-05-01T05:38:48Z  
-						);
+$BMButtonSearchFields = array(
+	'startdate' => '2025-01-01T00:00:00Z',		// Required.  Starting date for the search.  UTC/GMT format: 2009-08-24T05:38:48Z
+	'enddate' => '2025-12-31T23:59:59Z',		// Ending date for the search.  UTC/GMT format: 2010-05-01T05:38:48Z  
+);
 				
 $PayPalRequestData = array('BMButtonSearchFields'=>$BMButtonSearchFields);
 
diff --git a/samples/classic/BMCreateButton.php b/samples/classic/BMCreateButton.php
index fe32bf6a..87976009 100644
--- a/samples/classic/BMCreateButton.php
+++ b/samples/classic/BMCreateButton.php
@@ -5,24 +5,23 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-                    'PayPalAPIMode' => $api_mode,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+    'Sandbox' => $sandbox,
+    'PayPalAPIMode' => $api_mode,
+    'APIUsername' => $api_username,
+    'APIPassword' => $api_password,
+    'APISignature' => $api_signature, 
+    'PrintHeaders' => $print_headers, 
+    'LogResults' => $log_results,
+    'LogPath' => $log_path,
+);
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
-$BMCreateButtonFields = array
-						(
-						'buttoncode' => 'CLEARTEXT', 		// The kind of button code to create.  It is one of the following values:  HOSTED, ENCRYPTED, CLEARTEXT, TOKEN
-						'buttontype' => 'CART',			// Required.  The kind of button you want to create.  It is one of the following values:  BUYNOW, CART, GIFTCERTIFICATE, SUBSCRIBE, DONATE, UNSUBSCRIBE, VIEWCART, PAYMENTPLAN, AUTOBILLING, PAYMENT
-                        'buttonsubtype' => '',      // The use of button you want to create.  Values are:  PRODUCTS, SERVICES
+$BMCreateButtonFields = array(
+    'buttoncode' => 'CLEARTEXT',    // The kind of button code to create.  It is one of the following values:  HOSTED, ENCRYPTED, CLEARTEXT, TOKEN
+    'buttontype' => 'CART',			// Required.  The kind of button you want to create.  It is one of the following values:  BUYNOW, CART, GIFTCERTIFICATE, SUBSCRIBE, DONATE, UNSUBSCRIBE, VIEWCART, PAYMENTPLAN, AUTOBILLING, PAYMENT
+    'buttonsubtype' => '',          // The use of button you want to create.  Values are:  PRODUCTS, SERVICES
 );
 
 /**
@@ -34,70 +33,70 @@
  * https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
  */
 $BMButtonVars = array(
-    'notify_url' => '',                         // The URL to which PayPal posts information about the payment. in the form of an IPN message.
-    'amount' => '',                             // The price or amount of the product, service, or contribution, not including shipping, handling, or tax.  If this variable is omitted from Buy Now or Donate buttons, buyers enter their own amount at the time of the payment.
-    'discount_amount' => '',                    // Discount amount associated with an item.  Must be less than the selling price of the item.  Valid only for Buy Now and Add to Cart buttons.
-    'discount_amount2' => '',                   // Discount amount associated with each additional quantity of the item.  Must be equal to or less than the selling price of the item.
-    'discount_rate' => '',                      // Discount rate (percentage) associated with an item.  Must be set to a value less than 100.
-    'discount_rate2' => '',                     // Discount rate (percentage) associated with each additional quantity of the item.  Must be equal to or less than 100.
-    'discount_num' => '',                       // Number of additional quantities of the item to which the discount applies.
-    'item_name' => 'Test Widget',                          // Description of the item.  If this is omitted, buyers enter their own name during checkout.
-    'item_number' => '',                        // Pass-through variable for you to track product or service purchased or the contribution made.
-    'quantity' => '',                           // Number of items.
-    'shipping' => '',                           // The cost of shipping this item.
-    'shipping2' => '',                          // The cost of shipping each additional unit of this item.
-    'handling' => '',                           // handling charges.  This variable is not quantity-specific.
-    'tax' => '',                                // Transaction-based tax override variable.  Set this variable to a flat tax amount to apply to the payment regardless of the buyer's location.  This overrides any tax settings in the account profile.
-    'tax_rate' => '',                           // Transaction-based tax override variable.  Set this variable to a percentage that applies to the amount multipled by the quantity selected uring checkout.  This overrides your paypal account profile.
-    'undefined_quantity' =>'',                  // Set to 1 to allow the buyer to specify the quantity.
-    'weight' => '',                             // Weight of items.
-    'weight_unit' => '',                        // The unit of measure if weight is specified.  Values are:  lbs, kgs
-    'address_override' => '',                   // Set to 1 to override the payer's address stored in their PayPal account.
-    'currency_code' => '',                      // The currency of the payment.  https://developer.paypal.com/docs/classic/api/currency_codes/#id09A6G0U0GYK
-    'custom' => '',                             // Pass-through variable for your own tracking purposes, which buyers do not see.
-    'invoice' => '',                            // Pass-through variable you can use to identify your invoice number for the purchase.
-    'tax_cart' => '',                           // Cart-wide tax, overriding any individual item tax_ value
-    'handling_cart' => '',                      // Single handling fee charged cart-wide.
-    'weight_cart' => '',                        // If profile-based shipping rates are configured with a basis of weight, PayPal uses this value to calculate the shipping charges for the payment.  This value overrides the weight values of individual items.
-    'add' => '',                                // Set to 1 to add an item to the PayPal shopping cart.
-    'display' => '',                            // Set to 1 to display the contents of the PayPal shopping cart to the buyer.
-    'upload' => '',                             // Set to 1 to upload the contents of a third-party shopping cart or a custom shopping cart.
-    'business' => 'sandbo_1215254764_biz@angelleye.com',                           // Your PayPal ID or an email address associated with your PayPal account.  Email addresses must be confirmed.
-    'paymentaction' => '',                      // Indicates whether the payment is a finale sale or an authorization for a final sale, to be captured later.  Values are:  sale, authorization, order
-    'shopping_url' => '',                       // The URL of the page on the merchant website that buyers go to when they click the Continue Shopping button on the PayPal shopping cart page.
-    'a1' => '',                                 // Trial period 1 price.  For a free trial period, specify 0.
-    'p1' => '',                                 // Trial period 1 duration.  Required if you specify a1.
-    't1' => '',                                 // Trial period 1 units of duration.  Values are:  D, W, M, Y
-    'a2' => '',                                 // Trial period 2 price.  Can be specified only if you also specify a1.
-    'p2' => '',                                 // Trial period 2 duration.
-    't2' => '',                                 // Trial period 2 units of duration.
-    'a3' => '',                                 // Regular subscription price.
-    'p3' => '',                                 // Regular subscription duration.
-    't3' => '',                                 // Regular subscription units of duration.
-    'src' => '',                                // Recurring payments.  Subscription payments recur unless subscribers cancel.  Values are:  1, 0
-    'sra' => '',                                // Reattempt on failure.  If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling.  Values are:  1, 0
-    'no_note' => '',                            // Set to 1 to disable prompts for buyers to include a note with their payments.
-    'modify' => '',                             // Modification behavior.  0 - allows subscribers only to sign up for new subscriptions.  1 - allows subscribers to sign up for new subscriptions and modify their current subscriptions.  2 - allows subscribers to modify only their current subscriptions.
-    'usr_manage' => '',                         // Set to 1 to have PayPal generate usernames and passwords for subscribers.  https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscribe_buttons/#id08ADFB00QWS
-    'max_text' => '',                           // A description of the automatic billing plan.
-    'set_customer_limit' => '',                 // Specify whether to let buyers enter maximum billing limits in a text box or choose from a list of max billing limits that you specify.  Values are:  max_limit_own, max_limit_defined
-    'min_amount' => '',                         // The minimum monthly billing limit, if you have one.
-    'disp_tot' => '',                           // Display the total payment amount to buyers during checkout.  Values are:  Y, N
-    'page_style' => '',                         // The custom payment page style for checkout pages.  Values are:  paypal, primary, page_style_name
-    'image_url' => '',                          // The URL of the 150x50 image displayed as your logo on the PayPal checkout pages.
-    'cpp_cart_border_color' => '',              // The HTML hex code for your principal identifying color.  PayPal blends your color to white on the checkout pages.
-    'cpp_header_image' => '',                   // The image at the top, left of the checkout page.  Max size is 750x90.
-    'cpp_headerback_color' => '',               // The background color for the header of the checkout page.
-    'cpp_headerborder_color' => '',             // The border color around the header of the checkout page.
-    'cpp_logo_image' => '',                     // A URL to your logo image.  Must be .gif, .jpg, or .png.  190x60
-    'cpp_payflow_color' => '',                  // The background color for the checkout page below the header.
-    'lc' => '',                                 // The locale of the login or sign-up page.
-    'cn' => '',                                 // Label that appears above the note field.
-    'no_shipping' => '',                        // Do not prompt buyers for a shipping address.  Values are:  0 - prompt for an address but do not require.  1 - do not prompt.  2 - prompt and require address.
-    'return' => '',                             // The URL to which PayPal redirects buyers' browsers after they complete their payment.
-    'rm' => '',                                 // Return method.  Values are:  0 - all shopping cart payments use GET method.  1 - buyer's browser is redirected using the GET method. 2 - buyer's browser is redirected using POST.
-    'cbt' => '',                                // Sets the text for the Return to Merchant button on the PayPal completed payment page.
-    'cancel_return' => '',                      // A URL to which PayPal redirects buyers if they cancel the payment.
+    'notify_url' => '',                                     // The URL to which PayPal posts information about the payment. in the form of an IPN message.
+    'amount' => '',                                         // The price or amount of the product, service, or contribution, not including shipping, handling, or tax.  If this variable is omitted from Buy Now or Donate buttons, buyers enter their own amount at the time of the payment.
+    'discount_amount' => '',                                // Discount amount associated with an item.  Must be less than the selling price of the item.  Valid only for Buy Now and Add to Cart buttons.
+    'discount_amount2' => '',                               // Discount amount associated with each additional quantity of the item.  Must be equal to or less than the selling price of the item.
+    'discount_rate' => '',                                  // Discount rate (percentage) associated with an item.  Must be set to a value less than 100.
+    'discount_rate2' => '',                                 // Discount rate (percentage) associated with each additional quantity of the item.  Must be equal to or less than 100.
+    'discount_num' => '',                                   // Number of additional quantities of the item to which the discount applies.
+    'item_name' => 'Test Widget',                           // Description of the item.  If this is omitted, buyers enter their own name during checkout.
+    'item_number' => '',                                    // Pass-through variable for you to track product or service purchased or the contribution made.
+    'quantity' => '',                                       // Number of items.
+    'shipping' => '',                                       // The cost of shipping this item.
+    'shipping2' => '',                                      // The cost of shipping each additional unit of this item.
+    'handling' => '',                                       // handling charges.  This variable is not quantity-specific.
+    'tax' => '',                                            // Transaction-based tax override variable.  Set this variable to a flat tax amount to apply to the payment regardless of the buyer's location.  This overrides any tax settings in the account profile.
+    'tax_rate' => '',                                       // Transaction-based tax override variable.  Set this variable to a percentage that applies to the amount multipled by the quantity selected uring checkout.  This overrides your paypal account profile.
+    'undefined_quantity' =>'',                              // Set to 1 to allow the buyer to specify the quantity.
+    'weight' => '',                                         // Weight of items.
+    'weight_unit' => '',                                    // The unit of measure if weight is specified.  Values are:  lbs, kgs
+    'address_override' => '',                               // Set to 1 to override the payer's address stored in their PayPal account.
+    'currency_code' => '',                                  // The currency of the payment.  https://developer.paypal.com/docs/classic/api/currency_codes/#id09A6G0U0GYK
+    'custom' => '',                                         // Pass-through variable for your own tracking purposes, which buyers do not see.
+    'invoice' => '',                                        // Pass-through variable you can use to identify your invoice number for the purchase.
+    'tax_cart' => '',                                       // Cart-wide tax, overriding any individual item tax_ value
+    'handling_cart' => '',                                  // Single handling fee charged cart-wide.
+    'weight_cart' => '',                                    // If profile-based shipping rates are configured with a basis of weight, PayPal uses this value to calculate the shipping charges for the payment.  This value overrides the weight values of individual items.
+    'add' => '',                                            // Set to 1 to add an item to the PayPal shopping cart.
+    'display' => '',                                        // Set to 1 to display the contents of the PayPal shopping cart to the buyer.
+    'upload' => '',                                         // Set to 1 to upload the contents of a third-party shopping cart or a custom shopping cart.
+    'business' => 'sandbo_1215254764_biz@angelleye.com',    // Your PayPal ID or an email address associated with your PayPal account.  Email addresses must be confirmed.
+    'paymentaction' => '',                                  // Indicates whether the payment is a finale sale or an authorization for a final sale, to be captured later.  Values are:  sale, authorization, order
+    'shopping_url' => '',                                   // The URL of the page on the merchant website that buyers go to when they click the Continue Shopping button on the PayPal shopping cart page.
+    'a1' => '',                                             // Trial period 1 price.  For a free trial period, specify 0.
+    'p1' => '',                                             // Trial period 1 duration.  Required if you specify a1.
+    't1' => '',                                             // Trial period 1 units of duration.  Values are:  D, W, M, Y
+    'a2' => '',                                             // Trial period 2 price.  Can be specified only if you also specify a1.
+    'p2' => '',                                             // Trial period 2 duration.
+    't2' => '',                                             // Trial period 2 units of duration.
+    'a3' => '',                                             // Regular subscription price.
+    'p3' => '',                                             // Regular subscription duration.
+    't3' => '',                                             // Regular subscription units of duration.
+    'src' => '',                                            // Recurring payments.  Subscription payments recur unless subscribers cancel.  Values are:  1, 0
+    'sra' => '',                                            // Reattempt on failure.  If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling.  Values are:  1, 0
+    'no_note' => '',                                        // Set to 1 to disable prompts for buyers to include a note with their payments.
+    'modify' => '',                                         // Modification behavior.  0 - allows subscribers only to sign up for new subscriptions.  1 - allows subscribers to sign up for new subscriptions and modify their current subscriptions.  2 - allows subscribers to modify only their current subscriptions.
+    'usr_manage' => '',                                     // Set to 1 to have PayPal generate usernames and passwords for subscribers.  https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscribe_buttons/#id08ADFB00QWS
+    'max_text' => '',                                       // A description of the automatic billing plan.
+    'set_customer_limit' => '',                             // Specify whether to let buyers enter maximum billing limits in a text box or choose from a list of max billing limits that you specify.  Values are:  max_limit_own, max_limit_defined
+    'min_amount' => '',                                     // The minimum monthly billing limit, if you have one.
+    'disp_tot' => '',                                       // Display the total payment amount to buyers during checkout.  Values are:  Y, N
+    'page_style' => '',                                     // The custom payment page style for checkout pages.  Values are:  paypal, primary, page_style_name
+    'image_url' => '',                                      // The URL of the 150x50 image displayed as your logo on the PayPal checkout pages.
+    'cpp_cart_border_color' => '',                          // The HTML hex code for your principal identifying color.  PayPal blends your color to white on the checkout pages.
+    'cpp_header_image' => '',                               // The image at the top, left of the checkout page.  Max size is 750x90.
+    'cpp_headerback_color' => '',                           // The background color for the header of the checkout page.
+    'cpp_headerborder_color' => '',                         // The border color around the header of the checkout page.
+    'cpp_logo_image' => '',                                 // A URL to your logo image.  Must be .gif, .jpg, or .png.  190x60
+    'cpp_payflow_color' => '',                              // The background color for the checkout page below the header.
+    'lc' => '',                                             // The locale of the login or sign-up page.
+    'cn' => '',                                             // Label that appears above the note field.
+    'no_shipping' => '',                                    // Do not prompt buyers for a shipping address.  Values are:  0 - prompt for an address but do not require.  1 - do not prompt.  2 - prompt and require address.
+    'return' => '',                                         // The URL to which PayPal redirects buyers' browsers after they complete their payment.
+    'rm' => '',                                             // Return method.  Values are:  0 - all shopping cart payments use GET method.  1 - buyer's browser is redirected using the GET method. 2 - buyer's browser is redirected using POST.
+    'cbt' => '',                                            // Sets the text for the Return to Merchant button on the PayPal completed payment page.
+    'cancel_return' => '',                                  // A URL to which PayPal redirects buyers if they cancel the payment.
     'address1' => '',
     'address2' => '',
     'city' => '',
@@ -107,10 +106,10 @@
     'email' => '',
     'first_name' => '',
     'last_name' => '',
-    'charset' => '',                            // Sets the character set and character encoding for the billing login page.
-    'night_phone_a' => '',                      // Area code for US phone numbers or country code for phone numbers outside the US.
-    'night_phone_b' => '',                      // 3 digit prefix for US numbers or the entire phone number for numbers outside the US.
-    'night_phone_c' => '',                      // 4 digit phone number for US numbers.
+    'charset' => '',                                        // Sets the character set and character encoding for the billing login page.
+    'night_phone_a' => '',                                  // Area code for US phone numbers or country code for phone numbers outside the US.
+    'night_phone_b' => '',                                  // 3 digit prefix for US numbers or the entire phone number for numbers outside the US.
+    'night_phone_c' => '',                                  // 4 digit phone number for US numbers.
 );
 
 /**
diff --git a/samples/classic/BMGetButtonDetails.php b/samples/classic/BMGetButtonDetails.php
index b53d839a..7006558f 100644
--- a/samples/classic/BMGetButtonDetails.php
+++ b/samples/classic/BMGetButtonDetails.php
@@ -5,16 +5,17 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $HostedButtonID = 'SG9SQU2GBXJNA';
 $PayPalResult = $PayPal->BMGetButtonDetails($HostedButtonID);
diff --git a/samples/rest/AddBankAccount.php b/samples/rest/AddBankAccount.php
index f778d46d..fe675405 100644
--- a/samples/rest/AddBankAccount.php
+++ b/samples/rest/AddBankAccount.php
@@ -63,7 +63,7 @@
 );
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->Adaptive->AddBankAccount($PayPalRequestData);
+$PayPalResult = $PayPal->AddBankAccount($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/AddPaymentCard.php b/samples/rest/AddPaymentCard.php
new file mode 100644
index 00000000..9a177551
--- /dev/null
+++ b/samples/rest/AddPaymentCard.php
@@ -0,0 +1,81 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => '',
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'isAdaptive' => true,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$AddPaymentCardFields = array(		
+	'AccountID' => '', 						// The ID number of the PayPal account for which the payment card is being added.  You must specify either AccountID or EmailAdddress
+	'CardNumber' => '5581588041402157', 				// Required.  The credit card number.
+	'CardOwnerDateOfBirth' => '', 					// The date of birth of the card holder.
+	'CardType' => 'mastercard', 					// Required.  The type of card being added.  Values are:  Visa, MasterCard, AmericanExpress, Discover, SwitchMaestro, Solo, CarteAurore, CarteBleue, Cofinoga, 4etoiles, CarteAura, TarjetaAurora, JCB
+	'CardVerificationNumber' => '', 				// The verification code for the card.  Generally required for calls where ConfirmationType is set to NONE.  With the appropriate account review, this param is optional.
+	'ConfirmationType' => 'WEB', 					// Required.  Whether the account holder is redirected to PayPal.com to confirm the card addition.  Values are:  WEB, NONE
+	'CreateAccountKey' => '', 					// The key returned in a CreateAccount response.  Required for calls where the ConfirmationType is NONE.
+	'EmailAddress' => 'sandbo_1204199080_biz@angelleye.com', 	// Email address of the account holder adding the card.  Must specify either AccountID or EmailAddress.
+	'IssueNumber' => '', 						// The 2-digit issue number for Switch, Maestro, and Solo cards.
+	'StartDate' => '' 						// The element containing the start date for the payment card.
+);
+							
+$NameOnCard = array(
+	'Salutation' => '', 		// A salutation for the card owner.
+	'FirstName' => 'Tester', 	// Required.  First name of the card holder.
+	'MiddleName' => '', 		// Middle name of the card holder.
+	'LastName' => 'Testerson', 	// Required.  Last name of the card holder.
+	'Suffix' => ''			// A suffix for the card holder.
+);
+							
+$BillingAddress = array(
+	'Line1' => '123 Test Ave.', 	// Required.  Billing street address.
+	'Line2' => '', 			// Billing street address 2
+	'City' => 'Grandview', 		// Required.  Billing city.
+	'State' => 'MO', 		// Billing state.
+	'PostalCode' => '64030',	// Billing postal code
+	'CountryCode' => 'US'		// Required.  Billing country code.
+);
+
+$ExpirationDate = array(
+	'Month' => '12', 		// Expiration month.
+	'Year' => date('Y')		// Required.  Expiration Year.
+);
+							
+$WebOptions = array(
+	'CancelURL' => $domain.'cancel.php', 				// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => 'Cancel and return to website.', 	// A description for the CancelURL
+	'ReturnURL' => $domain.'return.php', 				// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => 'Return to website.'			// A description for the ReturnURL
+);
+
+$PayPalRequestData = array(
+	'AddPaymentCardFields' => $AddPaymentCardFields, 
+	'NameOnCard' => $NameOnCard, 
+	'BillingAddress' => $BillingAddress, 
+	'ExpirationDate' => $ExpirationDate, 
+	'WebOptions' => $WebOptions
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->AddPaymentCard($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/BMButtonSearch.php b/samples/rest/BMButtonSearch.php
new file mode 100644
index 00000000..74189b5a
--- /dev/null
+++ b/samples/rest/BMButtonSearch.php
@@ -0,0 +1,32 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$BMButtonSearchFields = array(
+	'startdate' => '2025-09-15T00:00:00Z',		// Required.  Starting date for the search.  UTC/GMT format: 2009-08-24T05:38:48Z
+	'enddate' => '2025-09-20T23:59:59Z',		// Ending date for the search.  UTC/GMT format: 2010-05-01T05:38:48Z  
+);
+				
+$PayPalRequestData = array('BMButtonSearchFields'=>$BMButtonSearchFields);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->BMButtonSearch($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/BMCreateButton.php b/samples/rest/BMCreateButton.php
index f5cfd797..4db871ef 100644
--- a/samples/rest/BMCreateButton.php
+++ b/samples/rest/BMCreateButton.php
@@ -32,70 +32,70 @@
  * https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
  */
 $BMButtonVars = array(
-    'notify_url' => '',                         // The URL to which PayPal posts information about the payment. in the form of an IPN message.
-    'amount' => '',                             // The price or amount of the product, service, or contribution, not including shipping, handling, or tax.  If this variable is omitted from Buy Now or Donate buttons, buyers enter their own amount at the time of the payment.
-    'discount_amount' => '',                    // Discount amount associated with an item.  Must be less than the selling price of the item.  Valid only for Buy Now and Add to Cart buttons.
-    'discount_amount2' => '',                   // Discount amount associated with each additional quantity of the item.  Must be equal to or less than the selling price of the item.
-    'discount_rate' => '',                      // Discount rate (percentage) associated with an item.  Must be set to a value less than 100.
-    'discount_rate2' => '',                     // Discount rate (percentage) associated with each additional quantity of the item.  Must be equal to or less than 100.
-    'discount_num' => '',                       // Number of additional quantities of the item to which the discount applies.
-    'item_name' => 'Test Widget',               // Description of the item.  If this is omitted, buyers enter their own name during checkout.
-    'item_number' => '',                        // Pass-through variable for you to track product or service purchased or the contribution made.
-    'quantity' => '',                           // Number of items.
-    'shipping' => '',                           // The cost of shipping this item.
-    'shipping2' => '',                          // The cost of shipping each additional unit of this item.
-    'handling' => '',                           // handling charges.  This variable is not quantity-specific.
-    'tax' => '',                                // Transaction-based tax override variable.  Set this variable to a flat tax amount to apply to the payment regardless of the buyer's location.  This overrides any tax settings in the account profile.
-    'tax_rate' => '',                           // Transaction-based tax override variable.  Set this variable to a percentage that applies to the amount multipled by the quantity selected uring checkout.  This overrides your paypal account profile.
-    'undefined_quantity' =>'',                  // Set to 1 to allow the buyer to specify the quantity.
-    'weight' => '',                             // Weight of items.
-    'weight_unit' => '',                        // The unit of measure if weight is specified.  Values are:  lbs, kgs
-    'address_override' => '',                   // Set to 1 to override the payer's address stored in their PayPal account.
-    'currency_code' => '',                      // The currency of the payment.  https://developer.paypal.com/docs/classic/api/currency_codes/#id09A6G0U0GYK
-    'custom' => '',                             // Pass-through variable for your own tracking purposes, which buyers do not see.
-    'invoice' => '',                            // Pass-through variable you can use to identify your invoice number for the purchase.
-    'tax_cart' => '',                           // Cart-wide tax, overriding any individual item tax_ value
-    'handling_cart' => '',                      // Single handling fee charged cart-wide.
-    'weight_cart' => '',                        // If profile-based shipping rates are configured with a basis of weight, PayPal uses this value to calculate the shipping charges for the payment.  This value overrides the weight values of individual items.
-    'add' => '',                                // Set to 1 to add an item to the PayPal shopping cart.
-    'display' => '',                            // Set to 1 to display the contents of the PayPal shopping cart to the buyer.
-    'upload' => '',                             // Set to 1 to upload the contents of a third-party shopping cart or a custom shopping cart.
-    'business' => 'sandbo_1215254764_biz@angelleye.com',                           // Your PayPal ID or an email address associated with your PayPal account.  Email addresses must be confirmed.
-    'paymentaction' => '',                      // Indicates whether the payment is a finale sale or an authorization for a final sale, to be captured later.  Values are:  sale, authorization, order
-    'shopping_url' => '',                       // The URL of the page on the merchant website that buyers go to when they click the Continue Shopping button on the PayPal shopping cart page.
-    'a1' => '',                                 // Trial period 1 price.  For a free trial period, specify 0.
-    'p1' => '',                                 // Trial period 1 duration.  Required if you specify a1.
-    't1' => '',                                 // Trial period 1 units of duration.  Values are:  D, W, M, Y
-    'a2' => '',                                 // Trial period 2 price.  Can be specified only if you also specify a1.
-    'p2' => '',                                 // Trial period 2 duration.
-    't2' => '',                                 // Trial period 2 units of duration.
-    'a3' => '',                                 // Regular subscription price.
-    'p3' => '',                                 // Regular subscription duration.
-    't3' => '',                                 // Regular subscription units of duration.
-    'src' => '',                                // Recurring payments.  Subscription payments recur unless subscribers cancel.  Values are:  1, 0
-    'sra' => '',                                // Reattempt on failure.  If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling.  Values are:  1, 0
-    'no_note' => '',                            // Set to 1 to disable prompts for buyers to include a note with their payments.
-    'modify' => '',                             // Modification behavior.  0 - allows subscribers only to sign up for new subscriptions.  1 - allows subscribers to sign up for new subscriptions and modify their current subscriptions.  2 - allows subscribers to modify only their current subscriptions.
-    'usr_manage' => '',                         // Set to 1 to have PayPal generate usernames and passwords for subscribers.  https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscribe_buttons/#id08ADFB00QWS
-    'max_text' => '',                           // A description of the automatic billing plan.
-    'set_customer_limit' => '',                 // Specify whether to let buyers enter maximum billing limits in a text box or choose from a list of max billing limits that you specify.  Values are:  max_limit_own, max_limit_defined
-    'min_amount' => '',                         // The minimum monthly billing limit, if you have one.
-    'disp_tot' => '',                           // Display the total payment amount to buyers during checkout.  Values are:  Y, N
-    'page_style' => '',                         // The custom payment page style for checkout pages.  Values are:  paypal, primary, page_style_name
-    'image_url' => '',                          // The URL of the 150x50 image displayed as your logo on the PayPal checkout pages.
-    'cpp_cart_border_color' => '',              // The HTML hex code for your principal identifying color.  PayPal blends your color to white on the checkout pages.
-    'cpp_header_image' => '',                   // The image at the top, left of the checkout page.  Max size is 750x90.
-    'cpp_headerback_color' => '',               // The background color for the header of the checkout page.
-    'cpp_headerborder_color' => '',             // The border color around the header of the checkout page.
-    'cpp_logo_image' => '',                     // A URL to your logo image.  Must be .gif, .jpg, or .png.  190x60
-    'cpp_payflow_color' => '',                  // The background color for the checkout page below the header.
-    'lc' => '',                                 // The locale of the login or sign-up page.
-    'cn' => '',                                 // Label that appears above the note field.
-    'no_shipping' => '',                        // Do not prompt buyers for a shipping address.  Values are:  0 - prompt for an address but do not require.  1 - do not prompt.  2 - prompt and require address.
-    'return' => '',                             // The URL to which PayPal redirects buyers' browsers after they complete their payment.
-    'rm' => '',                                 // Return method.  Values are:  0 - all shopping cart payments use GET method.  1 - buyer's browser is redirected using the GET method. 2 - buyer's browser is redirected using POST.
-    'cbt' => '',                                // Sets the text for the Return to Merchant button on the PayPal completed payment page.
-    'cancel_return' => '',                      // A URL to which PayPal redirects buyers if they cancel the payment.
+    'notify_url' => '',                                     // The URL to which PayPal posts information about the payment. in the form of an IPN message.
+    'amount' => '',                                         // The price or amount of the product, service, or contribution, not including shipping, handling, or tax.  If this variable is omitted from Buy Now or Donate buttons, buyers enter their own amount at the time of the payment.
+    'discount_amount' => '',                                // Discount amount associated with an item.  Must be less than the selling price of the item.  Valid only for Buy Now and Add to Cart buttons.
+    'discount_amount2' => '',                               // Discount amount associated with each additional quantity of the item.  Must be equal to or less than the selling price of the item.
+    'discount_rate' => '',                                  // Discount rate (percentage) associated with an item.  Must be set to a value less than 100.
+    'discount_rate2' => '',                                 // Discount rate (percentage) associated with each additional quantity of the item.  Must be equal to or less than 100.
+    'discount_num' => '',                                   // Number of additional quantities of the item to which the discount applies.
+    'item_name' => 'Test Widget',                           // Description of the item.  If this is omitted, buyers enter their own name during checkout.
+    'item_number' => '',                                    // Pass-through variable for you to track product or service purchased or the contribution made.
+    'quantity' => '',                                       // Number of items.
+    'shipping' => '',                                       // The cost of shipping this item.
+    'shipping2' => '',                                      // The cost of shipping each additional unit of this item.
+    'handling' => '',                                       // handling charges.  This variable is not quantity-specific.
+    'tax' => '',                                            // Transaction-based tax override variable.  Set this variable to a flat tax amount to apply to the payment regardless of the buyer's location.  This overrides any tax settings in the account profile.
+    'tax_rate' => '',                                       // Transaction-based tax override variable.  Set this variable to a percentage that applies to the amount multipled by the quantity selected uring checkout.  This overrides your paypal account profile.
+    'undefined_quantity' =>'',                              // Set to 1 to allow the buyer to specify the quantity.
+    'weight' => '',                                         // Weight of items.
+    'weight_unit' => '',                                    // The unit of measure if weight is specified.  Values are:  lbs, kgs
+    'address_override' => '',                               // Set to 1 to override the payer's address stored in their PayPal account.
+    'currency_code' => '',                                  // The currency of the payment.  https://developer.paypal.com/docs/classic/api/currency_codes/#id09A6G0U0GYK
+    'custom' => '',                                         // Pass-through variable for your own tracking purposes, which buyers do not see.
+    'invoice' => '',                                        // Pass-through variable you can use to identify your invoice number for the purchase.
+    'tax_cart' => '',                                       // Cart-wide tax, overriding any individual item tax_ value
+    'handling_cart' => '',                                  // Single handling fee charged cart-wide.
+    'weight_cart' => '',                                    // If profile-based shipping rates are configured with a basis of weight, PayPal uses this value to calculate the shipping charges for the payment.  This value overrides the weight values of individual items.
+    'add' => '',                                            // Set to 1 to add an item to the PayPal shopping cart.
+    'display' => '',                                        // Set to 1 to display the contents of the PayPal shopping cart to the buyer.
+    'upload' => '',                                         // Set to 1 to upload the contents of a third-party shopping cart or a custom shopping cart.
+    'business' => 'sandbo_1215254764_biz@angelleye.com',    // Your PayPal ID or an email address associated with your PayPal account.  Email addresses must be confirmed.
+    'paymentaction' => '',                                  // Indicates whether the payment is a finale sale or an authorization for a final sale, to be captured later.  Values are:  sale, authorization, order
+    'shopping_url' => '',                                   // The URL of the page on the merchant website that buyers go to when they click the Continue Shopping button on the PayPal shopping cart page.
+    'a1' => '',                                             // Trial period 1 price.  For a free trial period, specify 0.
+    'p1' => '',                                             // Trial period 1 duration.  Required if you specify a1.
+    't1' => '',                                             // Trial period 1 units of duration.  Values are:  D, W, M, Y
+    'a2' => '',                                             // Trial period 2 price.  Can be specified only if you also specify a1.
+    'p2' => '',                                             // Trial period 2 duration.
+    't2' => '',                                             // Trial period 2 units of duration.
+    'a3' => '',                                             // Regular subscription price.
+    'p3' => '',                                             // Regular subscription duration.
+    't3' => '',                                             // Regular subscription units of duration.
+    'src' => '',                                            // Recurring payments.  Subscription payments recur unless subscribers cancel.  Values are:  1, 0
+    'sra' => '',                                            // Reattempt on failure.  If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling.  Values are:  1, 0
+    'no_note' => '',                                        // Set to 1 to disable prompts for buyers to include a note with their payments.
+    'modify' => '',                                         // Modification behavior.  0 - allows subscribers only to sign up for new subscriptions.  1 - allows subscribers to sign up for new subscriptions and modify their current subscriptions.  2 - allows subscribers to modify only their current subscriptions.
+    'usr_manage' => '',                                     // Set to 1 to have PayPal generate usernames and passwords for subscribers.  https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscribe_buttons/#id08ADFB00QWS
+    'max_text' => '',                                       // A description of the automatic billing plan.
+    'set_customer_limit' => '',                             // Specify whether to let buyers enter maximum billing limits in a text box or choose from a list of max billing limits that you specify.  Values are:  max_limit_own, max_limit_defined
+    'min_amount' => '',                                     // The minimum monthly billing limit, if you have one.
+    'disp_tot' => '',                                       // Display the total payment amount to buyers during checkout.  Values are:  Y, N
+    'page_style' => '',                                     // The custom payment page style for checkout pages.  Values are:  paypal, primary, page_style_name
+    'image_url' => '',                                      // The URL of the 150x50 image displayed as your logo on the PayPal checkout pages.
+    'cpp_cart_border_color' => '',                          // The HTML hex code for your principal identifying color.  PayPal blends your color to white on the checkout pages.
+    'cpp_header_image' => '',                               // The image at the top, left of the checkout page.  Max size is 750x90.
+    'cpp_headerback_color' => '',                           // The background color for the header of the checkout page.
+    'cpp_headerborder_color' => '',                         // The border color around the header of the checkout page.
+    'cpp_logo_image' => '',                                 // A URL to your logo image.  Must be .gif, .jpg, or .png.  190x60
+    'cpp_payflow_color' => '',                              // The background color for the checkout page below the header.
+    'lc' => '',                                             // The locale of the login or sign-up page.
+    'cn' => '',                                             // Label that appears above the note field.
+    'no_shipping' => '',                                    // Do not prompt buyers for a shipping address.  Values are:  0 - prompt for an address but do not require.  1 - do not prompt.  2 - prompt and require address.
+    'return' => '',                                         // The URL to which PayPal redirects buyers' browsers after they complete their payment.
+    'rm' => '',                                             // Return method.  Values are:  0 - all shopping cart payments use GET method.  1 - buyer's browser is redirected using the GET method. 2 - buyer's browser is redirected using POST.
+    'cbt' => '',                                            // Sets the text for the Return to Merchant button on the PayPal completed payment page.
+    'cancel_return' => '',                                  // A URL to which PayPal redirects buyers if they cancel the payment.
     'address1' => '',
     'address2' => '',
     'city' => '',
@@ -105,10 +105,10 @@
     'email' => '',
     'first_name' => '',
     'last_name' => '',
-    'charset' => '',                            // Sets the character set and character encoding for the billing login page.
-    'night_phone_a' => '',                      // Area code for US phone numbers or country code for phone numbers outside the US.
-    'night_phone_b' => '',                      // 3 digit prefix for US numbers or the entire phone number for numbers outside the US.
-    'night_phone_c' => '',                      // 4 digit phone number for US numbers.
+    'charset' => '',                                        // Sets the character set and character encoding for the billing login page.
+    'night_phone_a' => '',                                  // Area code for US phone numbers or country code for phone numbers outside the US.
+    'night_phone_b' => '',                                  // 3 digit prefix for US numbers or the entire phone number for numbers outside the US.
+    'night_phone_c' => '',                                  // 4 digit phone number for US numbers.
 );
 
 /**
diff --git a/samples/rest/BMGetButtonDetails.php b/samples/rest/BMGetButtonDetails.php
new file mode 100644
index 00000000..ee8333fb
--- /dev/null
+++ b/samples/rest/BMGetButtonDetails.php
@@ -0,0 +1,24 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$HostedButtonID = 'SG9SQU2GBXJNA';
+$PayPalResult = $PayPal->BMGetButtonDetails($HostedButtonID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 4ad516fe..4f21cb43 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -17,9 +17,6 @@ class PayPalREST extends PayPal
 
     public function __construct($config)
     {
-        // Call parent constructor first
-        parent::__construct($config);
-
         $this->Sandbox = isset($config['Sandbox']) ? true : false;
 
         // Override base URL for REST API endpoints
@@ -124,8 +121,6 @@ private function getAccessToken()
      */
     protected function makeRequest($endpoint, $method = 'GET', $data = null)
     {
-        $token = $this->getAccessToken();
-
         $headers = $this->getHeaders(true);
 
         $ch = curl_init();
@@ -193,6 +188,118 @@ function GetBalance($DataArray)
         return $responseSimplified;
     }
 
+    function AddBankAccount($DataArray) {
+        $AddBankAccountFields = isset($DataArray['AddBankAccountFields']) ? $DataArray['AddBankAccountFields'] : array();
+        $WebOptions = isset($DataArray['WebOptions']) ? $DataArray['WebOptions'] : array();
+
+        $payload = array(
+            "account_number" => $AddBankAccountFields['BankAccountNumber'],
+            "routing_number" => $AddBankAccountFields['RoutingNumber'],
+            "account_type" => strtolower($AddBankAccountFields['BankAccountType']), // checking/savings
+            "bank_name" => $AddBankAccountFields['BankName'],
+            "country_code" => $AddBankAccountFields['BankCountryCode'],
+            "account_holder_name" => $AddBankAccountFields['BankName'] . " Holder", // Example
+            "confirmation_type" => strtoupper($AddBankAccountFields['ConfirmationType']), // WEB or NONE
+            "metadata" => array(
+                "email" => $AddBankAccountFields['EmailAddress'],
+                "return_url" => $WebOptions['ReturnURL'],
+                "cancel_url" => $WebOptions['CancelURL']
+            )
+        );
+
+        // Step 3: Make REST Call
+        $response = $this->makeRequest('/v1/vault/bank-accounts', 'POST', $payload);
+
+        // Step 4: Handle Response
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            return array(
+                'success' => true,
+                'status' => $response['status_code'],
+                'response' => $response
+            );
+        } else {
+            return array(
+                'success' => false,
+                'status' => $response['status_code'],
+                'error' => $response
+            );
+        }
+    }
+
+    function AddPaymentCard($DataArray) {
+        $AddPaymentCardFields = isset($DataArray['AddPaymentCardFields']) ? $DataArray['AddPaymentCardFields'] : array();
+        $NameOnCard = isset($DataArray['NameOnCard']) ? $DataArray['NameOnCard'] : array();
+        $BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array();
+        $ExpirationDate = isset($DataArray['ExpirationDate']) ? $DataArray['ExpirationDate'] : array();
+        $WebOptions = isset($DataArray['WebOptions']) ? $DataArray['WebOptions'] : array();
+
+        $payload = array(
+            'number' => $AddPaymentCardFields['CardNumber'],
+            'type' => $AddPaymentCardFields['CardType'],
+            'expire_month' => $ExpirationDate['Month'],
+            'expire_year' => $ExpirationDate['Year'],
+            'first_name' => $NameOnCard['FirstName'],
+            'last_name' => $NameOnCard['LastName'],
+            'billing_address' => array(
+                'line1' => $BillingAddress['Line1'],
+                'city' => $BillingAddress['City'],
+                'state' => $BillingAddress['State'],
+                'postal_code' => $BillingAddress['PostalCode'],
+                'country_code' => $BillingAddress['CountryCode']
+            )
+        );
+
+        // Step 3: Make REST Call
+        $response = $this->makeRequest('/v1/vault/credit-cards', 'POST', $payload);
+
+        $responseSimplified = [];
+
+        // Step 4: Handle Response
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            $responseSimplified = array(
+                'SUCCESS' => true,
+                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        } else {
+            $responseSimplified = array(
+                'SUCCESS' => false,
+                'STATUSCODE' => $response['status_code'],
+                'ERRORS' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
+    function BMButtonSearch($DataArray) {
+        $BMButtonSearchFields = isset($DataArray['BMButtonSearchFields']) ? $DataArray['BMButtonSearchFields'] : array();
+
+        $response = $this->makeRequest('/v1/reporting/transactions?start_date=' . $BMButtonSearchFields['startdate'] . '&end_date=' . $BMButtonSearchFields['enddate']);
+
+        $responseSimplified = [];
+
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            $responseSimplified = array(
+                'SUCCESS' => true,
+                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        } else {
+            $responseSimplified = array(
+                'SUCCESS' => false,
+                'STATUSCODE' => $response['status_code'],
+                'ERRORS' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
     /**
      * Test OAuth authentication
      */
diff --git a/templates/classic/AddPaymentCard.php b/templates/classic/AddPaymentCard.php
index f2e56b13..91ec51f7 100644
--- a/templates/classic/AddPaymentCard.php
+++ b/templates/classic/AddPaymentCard.php
@@ -3,78 +3,79 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => '',
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'isAdaptive' => true,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
-$AddPaymentCardFields = array(
-								'AccountID' => '', 												// The ID number of the PayPal account for which the payment card is being added.  You must specify either AccountID or EmailAdddress
-								'CardNumber' => '', 											// Required.  The credit card number.
-								'CardOwnerDateOfBirth' => '', 									// The date of birth of the card holder.
-								'CardType' => '', 												// Required.  The type of card being added.  Values are:  Visa, MasterCard, AmericanExpress, Discover, SwitchMaestro, Solo, CarteAurore, CarteBleue, Cofinoga, 4etoiles, CarteAura, TarjetaAurora, JCB
-								'CardVerificationNumber' => '', 								// The verification code for the card.  Generally required for calls where ConfirmationType is set to NONE.  With the appropriate account review, this param is optional.
-								'ConfirmationType' => '', 										// Required.  Whether the account holder is redirected to PayPal.com to confirm the card addition.  Values are:  WEB, NONE
-								'CreateAccountKey' => '', 										// The key returned in a CreateAccount response.  Required for calls where the ConfirmationType is NONE.
-								'EmailAddress' => '', 											// Email address of the account holder adding the card.  Must specify either AccountID or EmailAddress.
-								'IssueNumber' => '', 											// The 2-digit issue number for Switch, Maestro, and Solo cards.
-								'StartDate' => '' 												// The element containing the start date for the payment card.
-							);
+$AddPaymentCardFields = array(		
+	'AccountID' => '', 			// The ID number of the PayPal account for which the payment card is being added.  You must specify either AccountID or EmailAdddress
+	'CardNumber' => '', 			// Required.  The credit card number.
+	'CardOwnerDateOfBirth' => '', 		// The date of birth of the card holder.
+	'CardType' => '', 			// Required.  The type of card being added.  Values are:  Visa, MasterCard, AmericanExpress, Discover, SwitchMaestro, Solo, CarteAurore, CarteBleue, Cofinoga, 4etoiles, CarteAura, TarjetaAurora, JCB
+	'CardVerificationNumber' => '', 	// The verification code for the card.  Generally required for calls where ConfirmationType is set to NONE.  With the appropriate account review, this param is optional.
+	'ConfirmationType' => '', 		// Required.  Whether the account holder is redirected to PayPal.com to confirm the card addition.  Values are:  WEB, NONE
+	'CreateAccountKey' => '', 		// The key returned in a CreateAccount response.  Required for calls where the ConfirmationType is NONE.
+	'EmailAddress' => '', 			// Email address of the account holder adding the card.  Must specify either AccountID or EmailAddress.
+	'IssueNumber' => '', 			// The 2-digit issue number for Switch, Maestro, and Solo cards.
+	'StartDate' => '' 			// The element containing the start date for the payment card.
+);
 							
 $NameOnCard = array(
-					'Salutation' => '', 														// A salutation for the card owner.
-					'FirstName' => '', 															// Required.  First name of the card holder.
-					'MiddleName' => '', 														// Middle name of the card holder.
-					'LastName' => '', 															// Required.  Last name of the card holder.
-					'Suffix' => ''																// A suffix for the card holder.
-					);
+	'Salutation' => '', 		// A salutation for the card owner.
+	'FirstName' => '', 		// Required.  First name of the card holder.
+	'MiddleName' => '', 		// Middle name of the card holder.
+	'LastName' => '',	 	// Required.  Last name of the card holder.
+	'Suffix' => ''			// A suffix for the card holder.
+);
 							
 $BillingAddress = array(
-						'Line1' => '', 															// Required.  Billing street address.
-						'Line2' => '', 															// Billing street address 2
-						'City' => '', 															// Required.  Billing city.
-						'State' => '', 															// Billing state.
-						'PostalCode' => '',														// Billing postal code
-						'CountryCode' => ''														// Required.  Billing country code.
-						);
+	'Line1' => '', 		// Required.  Billing street address.
+	'Line2' => '', 		// Billing street address 2
+	'City' => '', 		// Required.  Billing city.
+	'State' => '', 		// Billing state.
+	'PostalCode' => '',	// Billing postal code
+	'CountryCode' => ''	// Required.  Billing country code.
+);
 
 $ExpirationDate = array(
-						'Month' => '', 															// Expiration month.
-						'Year' => ''															// Required.  Expiration Year.
-						);
+	'Month' => '', 		// Expiration month.
+	'Year' => ''		// Required.  Expiration Year.
+);
 							
 $WebOptions = array(
-					'CancelURL' => '', 															// The URL to which the user is returned when they cancel the flow at PayPal.com
-					'CancelURLDescription' => '', 												// A description for the CancelURL
-					'ReturnURL' => '', 															// The URL to which the user is returned when they complete the process.
-					'ReturnURLDescription' => ''												// A description for the ReturnURL
-					);
+	'CancelURL' => '', 			// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => '', 		// A description for the CancelURL
+	'ReturnURL' => '', 			// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => ''		// A description for the ReturnURL
+);
 
 $PayPalRequestData = array(
-						   'AddPaymentCardFields' => $AddPaymentCardFields, 
-						   'NameOnCard' => $NameOnCard, 
-						   'BillingAddress' => $BillingAddress, 
-						   'ExpirationDate' => $ExpirationDate, 
-						   'WebOptions' => $WebOptions
-						   );
+	'AddPaymentCardFields' => $AddPaymentCardFields, 
+	'NameOnCard' => $NameOnCard, 
+	'BillingAddress' => $BillingAddress, 
+	'ExpirationDate' => $ExpirationDate, 
+	'WebOptions' => $WebOptions
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->AddPaymentCard($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->AddPaymentCard($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/BMButtonSearch.php b/templates/classic/BMButtonSearch.php
index 7b8a1403..bac5c1a2 100644
--- a/templates/classic/BMButtonSearch.php
+++ b/templates/classic/BMButtonSearch.php
@@ -5,23 +5,23 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
 $PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
 
 // Prepare request arrays
-$BMButtonSearchFields = array
-						(
-						'startdate' => '', 			// Required.  Starting date for the search.  UTC/GMT format: 2009-08-24T05:38:48Z
-						'enddate' => ''				// Ending date for the search.  UTC/GMT format: 2010-05-01T05:38:48Z  
-						);
+$BMButtonSearchFields = array(
+	'startdate' => '', 		// Required.  Starting date for the search.  UTC/GMT format: 2009-08-24T05:38:48Z
+	'enddate' => ''			// Ending date for the search.  UTC/GMT format: 2010-05-01T05:38:48Z  
+);
 				
 $PayPalRequestData = array('BMButtonSearchFields'=>$BMButtonSearchFields);
 
diff --git a/templates/classic/BMCreateButton.php b/templates/classic/BMCreateButton.php
index 4fbcbe64..7346153a 100644
--- a/templates/classic/BMCreateButton.php
+++ b/templates/classic/BMCreateButton.php
@@ -5,23 +5,23 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+    'Sandbox' => $sandbox,
+    'PayPalAPIMode' => $api_mode,
+    'APIUsername' => $api_username,
+    'APIPassword' => $api_password,
+    'APISignature' => $api_signature, 
+    'PrintHeaders' => $print_headers, 
+    'LogResults' => $log_results,
+    'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
-$BMCreateButtonFields = array
-						(
-						'buttoncode' => '', 		// The kind of button code to create.  It is one of the following values:  HOSTED, ENCRYPTED, CLEARTEXT, TOKEN
-						'buttontype' => '',			// Required.  The kind of button you want to create.  It is one of the following values:  BUYNOW, CART, GIFTCERTIFICATE, SUBSCRIBE, DONATE, UNSUBSCRIBE, VIEWCART, PAYMENTPLAN, AUTOBILLING, PAYMENT
-                        'buttonsubtype' => '',      // The use of button you want to create.  Values are:  PRODUCTS, SERVICES
+$BMCreateButtonFields = array(
+    'buttoncode' => '', 		// The kind of button code to create.  It is one of the following values:  HOSTED, ENCRYPTED, CLEARTEXT, TOKEN
+    'buttontype' => '',			// Required.  The kind of button you want to create.  It is one of the following values:  BUYNOW, CART, GIFTCERTIFICATE, SUBSCRIBE, DONATE, UNSUBSCRIBE, VIEWCART, PAYMENTPLAN, AUTOBILLING, PAYMENT
+    'buttonsubtype' => '',      // The use of button you want to create.  Values are:  PRODUCTS, SERVICES
 );
 
 /**
diff --git a/templates/classic/BMGetButtonDetails.php b/templates/classic/BMGetButtonDetails.php
index e245f5e0..0e7e65f5 100644
--- a/templates/classic/BMGetButtonDetails.php
+++ b/templates/classic/BMGetButtonDetails.php
@@ -5,16 +5,17 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $HostedButtonID = '';
 $PayPalResult = $PayPal->BMGetButtonDetails($HostedButtonID);
diff --git a/templates/rest/AddBankAccount.php b/templates/rest/AddBankAccount.php
index c7807ee2..3ca9e595 100644
--- a/templates/rest/AddBankAccount.php
+++ b/templates/rest/AddBankAccount.php
@@ -64,7 +64,7 @@
 );
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->Adaptive->AddBankAccount($PayPalRequestData);
+$PayPalResult = $PayPal->AddBankAccount($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/AddPaymentCard.php b/templates/rest/AddPaymentCard.php
new file mode 100644
index 00000000..5fce12b4
--- /dev/null
+++ b/templates/rest/AddPaymentCard.php
@@ -0,0 +1,81 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => '',
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'isAdaptive' => true,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$AddPaymentCardFields = array(		
+	'AccountID' => '', 			// The ID number of the PayPal account for which the payment card is being added.  You must specify either AccountID or EmailAdddress
+	'CardNumber' => '', 			// Required.  The credit card number.
+	'CardOwnerDateOfBirth' => '', 		// The date of birth of the card holder.
+	'CardType' => '', 			// Required.  The type of card being added.  Values are:  Visa, MasterCard, AmericanExpress, Discover, SwitchMaestro, Solo, CarteAurore, CarteBleue, Cofinoga, 4etoiles, CarteAura, TarjetaAurora, JCB
+	'CardVerificationNumber' => '', 	// The verification code for the card.  Generally required for calls where ConfirmationType is set to NONE.  With the appropriate account review, this param is optional.
+	'ConfirmationType' => '', 		// Required.  Whether the account holder is redirected to PayPal.com to confirm the card addition.  Values are:  WEB, NONE
+	'CreateAccountKey' => '', 		// The key returned in a CreateAccount response.  Required for calls where the ConfirmationType is NONE.
+	'EmailAddress' => '', 			// Email address of the account holder adding the card.  Must specify either AccountID or EmailAddress.
+	'IssueNumber' => '', 			// The 2-digit issue number for Switch, Maestro, and Solo cards.
+	'StartDate' => '' 			// The element containing the start date for the payment card.
+);
+							
+$NameOnCard = array(
+	'Salutation' => '', 		// A salutation for the card owner.
+	'FirstName' => '', 		// Required.  First name of the card holder.
+	'MiddleName' => '', 		// Middle name of the card holder.
+	'LastName' => '',	 	// Required.  Last name of the card holder.
+	'Suffix' => ''			// A suffix for the card holder.
+);
+							
+$BillingAddress = array(
+	'Line1' => '', 		// Required.  Billing street address.
+	'Line2' => '', 		// Billing street address 2
+	'City' => '', 		// Required.  Billing city.
+	'State' => '', 		// Billing state.
+	'PostalCode' => '',	// Billing postal code
+	'CountryCode' => ''	// Required.  Billing country code.
+);
+
+$ExpirationDate = array(
+	'Month' => '', 		// Expiration month.
+	'Year' => ''		// Required.  Expiration Year.
+);
+							
+$WebOptions = array(
+	'CancelURL' => '', 			// The URL to which the user is returned when they cancel the flow at PayPal.com
+	'CancelURLDescription' => '', 		// A description for the CancelURL
+	'ReturnURL' => '', 			// The URL to which the user is returned when they complete the process.
+	'ReturnURLDescription' => ''		// A description for the ReturnURL
+);
+
+$PayPalRequestData = array(
+	'AddPaymentCardFields' => $AddPaymentCardFields, 
+	'NameOnCard' => $NameOnCard, 
+	'BillingAddress' => $BillingAddress, 
+	'ExpirationDate' => $ExpirationDate, 
+	'WebOptions' => $WebOptions
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->AddPaymentCard($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/BMButtonSearch.php b/templates/rest/BMButtonSearch.php
new file mode 100644
index 00000000..72f9884f
--- /dev/null
+++ b/templates/rest/BMButtonSearch.php
@@ -0,0 +1,32 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$BMButtonSearchFields = array(
+	'startdate' => '',		// Required.  Starting date for the search.  UTC/GMT format: 2009-08-24T05:38:48Z
+	'enddate' => '',		// Ending date for the search.  UTC/GMT format: 2010-05-01T05:38:48Z  
+);
+				
+$PayPalRequestData = array('BMButtonSearchFields'=>$BMButtonSearchFields);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->BMButtonSearch($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/BMCreateButton.php b/templates/rest/BMCreateButton.php
new file mode 100644
index 00000000..f1db8278
--- /dev/null
+++ b/templates/rest/BMCreateButton.php
@@ -0,0 +1,154 @@
+ $sandbox,
+    'PayPalAPIMode' => $api_mode,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret,
+    'PrintHeaders' => $print_headers, 
+    'LogResults' => $log_results,
+    'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$BMCreateButtonFields = array(
+    'buttoncode' => '', 		// The kind of button code to create.  It is one of the following values:  HOSTED, ENCRYPTED, CLEARTEXT, TOKEN
+    'buttontype' => '',			// Required.  The kind of button you want to create.  It is one of the following values:  BUYNOW, CART, GIFTCERTIFICATE, SUBSCRIBE, DONATE, UNSUBSCRIBE, VIEWCART, PAYMENTPLAN, AUTOBILLING, PAYMENT
+    'buttonsubtype' => '',      // The use of button you want to create.  Values are:  PRODUCTS, SERVICES
+);
+
+/**
+ * You may pass in any variables from the Standard Payments list.
+ *
+ * Depending on the type of button you are creating some variables will be required.
+ * Refer to the HTML Standard Variable reference for more details on variables for specific button types.
+ *
+ * https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
+ */
+$BMButtonVars = array(
+    'notify_url' => '',                         // The URL to which PayPal posts information about the payment. in the form of an IPN message.
+    'amount' => '',                             // The price or amount of the product, service, or contribution, not including shipping, handling, or tax.  If this variable is omitted from Buy Now or Donate buttons, buyers enter their own amount at the time of the payment.
+    'discount_amount' => '',                    // Discount amount associated with an item.  Must be less than the selling price of the item.  Valid only for Buy Now and Add to Cart buttons.
+    'discount_amount2' => '',                   // Discount amount associated with each additional quantity of the item.  Must be equal to or less than the selling price of the item.
+    'discount_rate' => '',                      // Discount rate (percentage) associated with an item.  Must be set to a value less than 100.
+    'discount_rate2' => '',                     // Discount rate (percentage) associated with each additional quantity of the item.  Must be equal to or less than 100.
+    'discount_num' => '',                       // Number of additional quantities of the item to which the discount applies.
+    'item_name' => '',                          // Description of the item.  If this is omitted, buyers enter their own name during checkout.
+    'item_number' => '',                        // Pass-through variable for you to track product or service purchased or the contribution made.
+    'quantity' => '',                           // Number of items.
+    'shipping' => '',                           // The cost of shipping this item.
+    'shipping2' => '',                          // The cost of shipping each additional unit of this item.
+    'handling' => '',                           // handling charges.  This variable is not quantity-specific.
+    'tax' => '',                                // Transaction-based tax override variable.  Set this variable to a flat tax amount to apply to the payment regardless of the buyer's location.  This overrides any tax settings in the account profile.
+    'tax_rate' => '',                           // Transaction-based tax override variable.  Set this variable to a percentage that applies to the amount multipled by the quantity selected uring checkout.  This overrides your paypal account profile.
+    'undefined_quantity' =>'',                  // Set to 1 to allow the buyer to specify the quantity.
+    'weight' => '',                             // Weight of items.
+    'weight_unit' => '',                        // The unit of measure if weight is specified.  Values are:  lbs, kgs
+    'address_override' => '',                   // Set to 1 to override the payer's address stored in their PayPal account.
+    'currency_code' => '',                      // The currency of the payment.  https://developer.paypal.com/docs/classic/api/currency_codes/#id09A6G0U0GYK
+    'custom' => '',                             // Pass-through variable for your own tracking purposes, which buyers do not see.
+    'invoice' => '',                            // Pass-through variable you can use to identify your invoice number for the purchase.
+    'tax_cart' => '',                           // Cart-wide tax, overriding any individual item tax_ value
+    'handling_cart' => '',                      // Single handling fee charged cart-wide.
+    'weight_cart' => '',                        // If profile-based shipping rates are configured with a basis of weight, PayPal uses this value to calculate the shipping charges for the payment.  This value overrides the weight values of individual items.
+    'add' => '',                                // Set to 1 to add an item to the PayPal shopping cart.
+    'display' => '',                            // Set to 1 to display the contents of the PayPal shopping cart to the buyer.
+    'upload' => '',                             // Set to 1 to upload the contents of a third-party shopping cart or a custom shopping cart.
+    'business' => '',                           // Your PayPal ID or an email address associated with your PayPal account.  Email addresses must be confirmed.
+    'paymentaction' => '',                      // Indicates whether the payment is a finale sale or an authorization for a final sale, to be captured later.  Values are:  sale, authorization, order
+    'shopping_url' => '',                       // The URL of the page on the merchant website that buyers go to when they click the Continue Shopping button on the PayPal shopping cart page.
+    'a1' => '',                                 // Trial period 1 price.  For a free trial period, specify 0.
+    'p1' => '',                                 // Trial period 1 duration.  Required if you specify a1.
+    't1' => '',                                 // Trial period 1 units of duration.  Values are:  D, W, M, Y
+    'a2' => '',                                 // Trial period 2 price.  Can be specified only if you also specify a1.
+    'p2' => '',                                 // Trial period 2 duration.
+    't2' => '',                                 // Trial period 2 units of duration.
+    'a3' => '',                                 // Regular subscription price.
+    'p3' => '',                                 // Regular subscription duration.
+    't3' => '',                                 // Regular subscription units of duration.
+    'src' => '',                                // Recurring payments.  Subscription payments recur unless subscribers cancel.  Values are:  1, 0
+    'sra' => '',                                // Reattempt on failure.  If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling.  Values are:  1, 0
+    'no_note' => '',                            // Set to 1 to disable prompts for buyers to include a note with their payments.
+    'modify' => '',                             // Modification behavior.  0 - allows subscribers only to sign up for new subscriptions.  1 - allows subscribers to sign up for new subscriptions and modify their current subscriptions.  2 - allows subscribers to modify only their current subscriptions.
+    'usr_manage' => '',                         // Set to 1 to have PayPal generate usernames and passwords for subscribers.  https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscribe_buttons/#id08ADFB00QWS
+    'max_text' => '',                           // A description of the automatic billing plan.
+    'set_customer_limit' => '',                 // Specify whether to let buyers enter maximum billing limits in a text box or choose from a list of max billing limits that you specify.  Values are:  max_limit_own, max_limit_defined
+    'min_amount' => '',                         // The minimum monthly billing limit, if you have one.
+    'disp_tot' => '',                           // Display the total payment amount to buyers during checkout.  Values are:  Y, N
+    'page_style' => '',                         // The custom payment page style for checkout pages.  Values are:  paypal, primary, page_style_name
+    'image_url' => '',                          // The URL of the 150x50 image displayed as your logo on the PayPal checkout pages.
+    'cpp_cart_border_color' => '',              // The HTML hex code for your principal identifying color.  PayPal blends your color to white on the checkout pages.
+    'cpp_header_image' => '',                   // The image at the top, left of the checkout page.  Max size is 750x90.
+    'cpp_headerback_color' => '',               // The background color for the header of the checkout page.
+    'cpp_headerborder_color' => '',             // The border color around the header of the checkout page.
+    'cpp_logo_image' => '',                     // A URL to your logo image.  Must be .gif, .jpg, or .png.  190x60
+    'cpp_payflow_color' => '',                  // The background color for the checkout page below the header.
+    'lc' => '',                                 // The locale of the login or sign-up page.
+    'cn' => '',                                 // Label that appears above the note field.
+    'no_shipping' => '',                        // Do not prompt buyers for a shipping address.  Values are:  0 - prompt for an address but do not require.  1 - do not prompt.  2 - prompt and require address.
+    'return' => '',                             // The URL to which PayPal redirects buyers' browsers after they complete their payment.
+    'rm' => '',                                 // Return method.  Values are:  0 - all shopping cart payments use GET method.  1 - buyer's browser is redirected using the GET method. 2 - buyer's browser is redirected using POST.
+    'cbt' => '',                                // Sets the text for the Return to Merchant button on the PayPal completed payment page.
+    'cancel_return' => '',                      // A URL to which PayPal redirects buyers if they cancel the payment.
+    'address1' => '',
+    'address2' => '',
+    'city' => '',
+    'state' => '',
+    'zip' => '',
+    'country' => '',
+    'email' => '',
+    'first_name' => '',
+    'last_name' => '',
+    'charset' => '',                            // Sets the character set and character encoding for the billing login page.
+    'night_phone_a' => '',                      // Area code for US phone numbers or country code for phone numbers outside the US.
+    'night_phone_b' => '',                      // 3 digit prefix for US numbers or the entire phone number for numbers outside the US.
+    'night_phone_c' => '',                      // 4 digit phone number for US numbers.
+);
+
+/**
+ * Button options are handled similar to order items in other calls within this library.
+ * You will need to setup a nested array of options and option selections.
+ *
+ * You could end up with multiple $BMButtonOption arrays here, and each of those could
+ * contain multiple $BMButtonOptionSelection arrays within it.  All are then passed into
+ * the final $BMButtonOptions array that gets passed to the API.
+ */
+$BMButtonOptions = array();
+
+$BMButtonOptionSelections = array();
+$BMButtonOptionSelection = array(
+    'value' => '',
+    'price' => '',
+    'type' => ''
+);
+array_push($BMButtonOptionSelections, $BMButtonOptionSelection);
+
+$BMButtonOption = array(
+    'name' => '',
+    'selections' => $BMButtonOptionSelections
+);
+array_push($BMButtonOptions, $BMButtonOption);
+
+$BMButtonOption = array(
+    'name' => 'Size',
+    'selections' => $BMButtonOptionSelections
+);
+array_push($BMButtonOptions, $BMButtonOption);
+
+$PayPalRequestData = array(
+    'BMCreateButtonFields' => $BMCreateButtonFields,
+    'BMButtonVars' => $BMButtonVars,
+    'BMButtonOptions' => $BMButtonOptions
+);
+
+$PayPalResult = $PayPal->BMCreateButton($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/templates/rest/BMGetButtonDetails.php b/templates/rest/BMGetButtonDetails.php
new file mode 100644
index 00000000..cc0976c2
--- /dev/null
+++ b/templates/rest/BMGetButtonDetails.php
@@ -0,0 +1,24 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$HostedButtonID = '';
+$PayPalResult = $PayPal->BMGetButtonDetails($HostedButtonID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file

From 44d03d871d98ca0719e611c06d0d2203b867ef45 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Fri, 24 Oct 2025 10:04:07 +0530
Subject: [PATCH 015/146] Minor Code Added

---
 src/angelleye/PayPal/PayPalREST.php | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)

diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 4f21cb43..16a5252e 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -300,6 +300,30 @@ function BMButtonSearch($DataArray) {
         return $responseSimplified;
     }
 
+    function BMGetButtonDetails($HostedButtonID) {
+        $response = $this->makeRequest('/v1/checkout/orders/' . $HostedButtonID);
+
+        $responseSimplified = [];
+
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            $responseSimplified = array(
+                'SUCCESS' => true,
+                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        } else {
+            $responseSimplified = array(
+                'SUCCESS' => false,
+                'STATUSCODE' => $response['status_code'],
+                'ERRORS' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
     /**
      * Test OAuth authentication
      */

From 3313445c57f4e02ff9218c67ac9fe277d2b38a4f Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Fri, 24 Oct 2025 17:33:37 +0530
Subject: [PATCH 016/146] Completed SetExpressCheckout and
 DoExpressCheckoutPayment

---
 samples/classic/DoExpressCheckoutPayment.php  | 193 ++++++------
 samples/classic/SetExpressCheckout.php        | 275 +++++++++---------
 samples/rest/DoExpressCheckoutPayment.php     |  26 ++
 samples/rest/SetExpressCheckout.php           | 193 ++++++++++++
 src/angelleye/PayPal/PayPalREST.php           | 102 +++++++
 .../classic/DoExpressCheckoutPayment.php      | 195 +++++++------
 templates/classic/SetExpressCheckout.php      | 257 ++++++++--------
 templates/rest/DoExpressCheckoutPayment.php   |  29 ++
 templates/rest/SetExpressCheckout.php         | 185 ++++++++++++
 9 files changed, 997 insertions(+), 458 deletions(-)
 create mode 100644 samples/rest/DoExpressCheckoutPayment.php
 create mode 100644 samples/rest/SetExpressCheckout.php
 create mode 100644 templates/rest/DoExpressCheckoutPayment.php
 create mode 100644 templates/rest/SetExpressCheckout.php

diff --git a/samples/classic/DoExpressCheckoutPayment.php b/samples/classic/DoExpressCheckoutPayment.php
index 897e0787..61c1ef2b 100644
--- a/samples/classic/DoExpressCheckoutPayment.php
+++ b/samples/classic/DoExpressCheckoutPayment.php
@@ -3,16 +3,17 @@
 require_once('../../autoload.php');
 
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 /*
  * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal
@@ -23,110 +24,110 @@
 echo '

'; $DECPFields = array( - 'token' => $_SESSION['SetExpressCheckoutResult']['TOKEN'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. - 'payerid' => $GECDResult['PAYERID'], // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. - 'returnfmfdetails' => '1', // Flag to indicate whether you want the results returned by Fraud Management Filters or not. 1 or 0. - 'giftmessage' => '', // The gift message entered by the buyer on the PayPal Review page. 150 char max. - 'giftreceiptenable' => '', // Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false. - 'giftwrapname' => '', // The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer. - 'giftwrapamount' => '', // The amount only if the gift option on the PayPal Review page was selected by the buyer. - 'buyermarketingemail' => '', // The buyer email address opted in by the buyer on the PayPal Review page. - 'surveyquestion' => '', // The survey question on the PayPal Review page. 50 char max. - 'surveychoiceselected' => '', // The survey response selected by the buyer on the PayPal Review page. 15 char max. - 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. - 'buttonsource' => '' // ID code for use by third-party apps to identify transactions in PayPal. - ); + 'token' => $_SESSION['SetExpressCheckoutResult']['TOKEN'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. + 'payerid' => $GECDResult['PAYERID'], // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. + 'returnfmfdetails' => '1', // Flag to indicate whether you want the results returned by Fraud Management Filters or not. 1 or 0. + 'giftmessage' => '', // The gift message entered by the buyer on the PayPal Review page. 150 char max. + 'giftreceiptenable' => '', // Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false. + 'giftwrapname' => '', // The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer. + 'giftwrapamount' => '', // The amount only if the gift option on the PayPal Review page was selected by the buyer. + 'buyermarketingemail' => '', // The buyer email address opted in by the buyer on the PayPal Review page. + 'surveyquestion' => '', // The survey question on the PayPal Review page. 50 char max. + 'surveychoiceselected' => '', // The survey response selected by the buyer on the PayPal Review page. 15 char max. + 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. + 'buttonsource' => '' // ID code for use by third-party apps to identify transactions in PayPal. +); $Payments = array(); $Payment = array( - 'amt' => '100.00', // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - 'itemamt' => '80.00', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. - 'shippingamt' => '15.00', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. - 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount. If true, the total shipping insurance for this order must be a positive number. - 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. - 'taxamt' => '5.00', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. - 'desc' => 'This is a test order.', // Description of items on the order. 127 char max. - 'custom' => '', // Free-form field for your own use. 256 char max. - 'invnum' => '', // Your own invoice or tracking number. 127 char max. - 'notifyurl' => '', // URL for receiving Instant Payment Notifications - 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. - 'shiptostreet2' => '', // Second street address. 100 char max. - 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => '', // Phone number for shipping address. 20 char max. - 'notetext' => 'This is a test note before ever having left the web site.', // Note to the merchant. 255 char max. - 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. - 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. - 'paymentrequestid' => '', // A unique identifier of the specific payment request, which is required for parallel payments. - 'sellerpaypalaccountid' => '' // A unique identifier for the merchant. For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant. - ); + 'amt' => '100.00', // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'currencycode' => 'USD', // A three-character currency code. Default is USD. + 'itemamt' => '80.00', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. + 'shippingamt' => '15.00', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount. If true, the total shipping insurance for this order must be a positive number. + 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => '5.00', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'desc' => 'This is a test order.', // Description of items on the order. 127 char max. + 'custom' => '', // Free-form field for your own use. 256 char max. + 'invnum' => '', // Your own invoice or tracking number. 127 char max. + 'notifyurl' => '', // URL for receiving Instant Payment Notifications + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '', // Phone number for shipping address. 20 char max. + 'notetext' => 'This is a test note before ever having left the web site.', // Note to the merchant. 255 char max. + 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. + 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. + 'paymentrequestid' => '', // A unique identifier of the specific payment request, which is required for parallel payments. + 'sellerpaypalaccountid' => '' // A unique identifier for the merchant. For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant. +); $PaymentOrderItems = array(); $Item = array( - 'name' => 'Widget 123', // Item name. 127 char max. - 'desc' => 'Widget 123', // Item description. 127 char max. - 'amt' => '40.00', // Cost of item. - 'number' => '123', // Item number. 127 char max. - 'qty' => '1', // Item qty on order. Any positive integer. - 'taxamt' => '', // Item sales tax - 'itemurl' => 'http://www.angelleye.com/products/123.php', // URL for the item. - 'itemweightvalue' => '', // The weight value of the item. - 'itemweightunit' => '', // The weight unit of the item. - 'itemheightvalue' => '', // The height value of the item. - 'itemheightunit' => '', // The height unit of the item. - 'itemwidthvalue' => '', // The width value of the item. - 'itemwidthunit' => '', // The width unit of the item. - 'itemlengthvalue' => '', // The length value of the item. - 'itemlengthunit' => '', // The length unit of the item. - 'ebayitemnumber' => '', // Auction item number. - 'ebayitemauctiontxnid' => '', // Auction transaction ID number. - 'ebayitemorderid' => '', // Auction order ID number. - 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters - ); + 'name' => 'Widget 123', // Item name. 127 char max. + 'desc' => 'Widget 123', // Item description. 127 char max. + 'amt' => '40.00', // Cost of item. + 'number' => '123', // Item number. 127 char max. + 'qty' => '1', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => 'http://www.angelleye.com/products/123.php', // URL for the item. + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); array_push($PaymentOrderItems, $Item); $Item = array( - 'name' => 'Widget 456', // Item name. 127 char max. - 'desc' => 'Widget 456', // Item description. 127 char max. - 'amt' => '40.00', // Cost of item. - 'number' => '456', // Item number. 127 char max. - 'qty' => '1', // Item qty on order. Any positive integer. - 'taxamt' => '', // Item sales tax - 'itemurl' => 'http://www.angelleye.com/products/456.php', // URL for the item. - 'itemweightvalue' => '', // The weight value of the item. - 'itemweightunit' => '', // The weight unit of the item. - 'itemheightvalue' => '', // The height value of the item. - 'itemheightunit' => '', // The height unit of the item. - 'itemwidthvalue' => '', // The width value of the item. - 'itemwidthunit' => '', // The width unit of the item. - 'itemlengthvalue' => '', // The length value of the item. - 'itemlengthunit' => '', // The length unit of the item. - 'ebayitemnumber' => '', // Auction item number. - 'ebayitemauctiontxnid' => '', // Auction transaction ID number. - 'ebayitemorderid' => '', // Auction order ID number. - 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters - ); + 'name' => 'Widget 456', // Item name. 127 char max. + 'desc' => 'Widget 456', // Item description. 127 char max. + 'amt' => '40.00', // Cost of item. + 'number' => '456', // Item number. 127 char max. + 'qty' => '1', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => 'http://www.angelleye.com/products/456.php', // URL for the item. + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); array_push($PaymentOrderItems, $Item); $Payment['order_items'] = $PaymentOrderItems; array_push($Payments, $Payment); $UserSelectedOptions = array( - 'shippingcalculationmode' => '', // Describes how the options that were presented to the user were determined. values are: API - Callback or API - Flatrate. - 'insuranceoptionselected' => '', // The Yes/No option that you chose for insurance. - 'shippingoptionisdefault' => '', // Is true if the buyer chose the default shipping option. - 'shippingoptionamount' => '', // The shipping amount that was chosen by the buyer. - 'shippingoptionname' => '', // Is true if the buyer chose the default shipping option...?? Maybe this is supposed to show the name..?? - ); + 'shippingcalculationmode' => '', // Describes how the options that were presented to the user were determined. values are: API - Callback or API - Flatrate. + 'insuranceoptionselected' => '', // The Yes/No option that you chose for insurance. + 'shippingoptionisdefault' => '', // Is true if the buyer chose the default shipping option. + 'shippingoptionamount' => '', // The shipping amount that was chosen by the buyer. + 'shippingoptionname' => '', // Is true if the buyer chose the default shipping option...?? Maybe this is supposed to show the name..?? +); $PayPalRequest = array( - 'DECPFields' => $DECPFields, - 'Payments' => $Payments - ); + 'DECPFields' => $DECPFields, + 'Payments' => $Payments +); $_SESSION['PayPalResult'] = $PayPal -> DoExpressCheckoutPayment($PayPalRequest); diff --git a/samples/classic/SetExpressCheckout.php b/samples/classic/SetExpressCheckout.php index 70c0f614..03c961c4 100644 --- a/samples/classic/SetExpressCheckout.php +++ b/samples/classic/SetExpressCheckout.php @@ -5,176 +5,177 @@ require_once('../../autoload.php'); $PayPalConfig = array( - 'Sandbox' => $sandbox, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'APIVersion' => '97.0', - 'APISubject' => '', - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - ); + 'Sandbox' => $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APIVersion' => '97.0', + 'APISubject' => '', + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); -$PayPal = new angelleye\PayPal\PayPal($PayPalConfig); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); $SECFields = array( - 'token' => '', // A timestamped token, the value of which was returned by a previous SetExpressCheckout call. - 'maxamt' => '200.00', // The expected maximum total amount the order will be, including S&H and sales tax. - 'returnurl' => $domain . 'samples/DoExpressCheckoutPayment.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. - 'cancelurl' => $domain . 'paypal/class/cancel.php', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. - 'callback' => '', // URL to which the callback request from PayPal is sent. Must start with https:// for production. - 'callbacktimeout' => '', // An override for you to request more or less time to be able to process the callback request and response. Acceptable range for override is 1-6 seconds. If you specify greater than 6 PayPal will use default value of 3 seconds. - 'callbackversion' => '', // The version of the Instant Update API you're using. The default is the current version. - 'reqconfirmshipping' => '0', // The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal. This overrides anything in the account profile. Possible values are 1 or 0. - 'noshipping' => '1', // The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed. Maybe 1 or 0. - 'addroverride' => '', // The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal. This does not allow the customer to edit the address here. Must be 1 or 0. - 'localecode' => '', // Locale of pages displayed by PayPal during checkout. Should be a 2 character country code. You can retrive the country code by passing the country name into the class' GetCountryCode() function. - 'pagestyle' => '', // Sets the Custom Payment Page Style for payment pages associated with this button/link. - 'hdrimg' => '', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. - 'hdrbordercolor' => '', // Sets the border color around the header of the payment page. The border is a 2-pixel permiter around the header space. Default is black. - 'hdrbackcolor' => '', // Sets the background color for the header of the payment page. Default is white. - 'payflowcolor' => '', // Sets the background color for the payment page. Default is white. - 'skipdetails' => '', // This is a custom field not included in the PayPal documentation. It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not. See PayPal docs for more info. - 'email' => '', // Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal sign-in page. 127 char max. - 'solutiontype' => 'Sole', // Type of checkout flow. Must be Sole (express checkout for auctions) or Mark (normal express checkout) - 'landingpage' => 'Billing', // Type of PayPal page to display. Can be Billing or Login. If billing it shows a full credit card form. If Login it just shows the login screen. - 'channeltype' => '', // Type of channel. Must be Merchant (non-auction seller) or eBayItem (eBay auction) - 'giropaysuccessurl' => '', // The URL on the merchant site to redirect to after a successful giropay payment. Only use this field if you are using giropay or bank transfer payment methods in Germany. - 'giropaycancelurl' => '', // The URL on the merchant site to redirect to after a canceled giropay payment. Only use this field if you are using giropay or bank transfer methods in Germany. - 'banktxnpendingurl' => '', // The URL on the merchant site to transfer to after a bank transfter payment. Use this field only if you are using giropay or bank transfer methods in Germany. - 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. - 'customerservicenumber' => '555-555-5555', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. - 'giftmessageenable' => '1', // Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1 - 'giftreceiptenable' => '1', // Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1 - 'giftwrapenable' => '1', // Enable gift wrap widget on the PayPal Review page. Allowable values are 0 and 1. - 'giftwrapname' => 'Box with Ribbon', // Label for the gift wrap option such as "Box with ribbon". 25 char max. - 'giftwrapamount' => '2.50', // Amount charged for gift-wrap service. - 'buyeremailoptionenable' => '1', // Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1 - 'surveyquestion' => '', // Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present. 50 char max. - 'surveyenable' => '1', // Enable survey functionality. Allowable values are 0 and 1 - 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max. - 'buyerusername' => '', // The user name of the user at the marketplaces site. - 'buyerregistrationdate' => '2012-07-14T00:00:00Z', // Date when the user registered with the marketplace. - 'allowpushfunding' => '' // Whether the merchant can accept push funding. 0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding. - ); + 'token' => '', // A timestamped token, the value of which was returned by a previous SetExpressCheckout call. + 'maxamt' => '200.00', // The expected maximum total amount the order will be, including S&H and sales tax. + 'returnurl' => 'http://localhost:8888/paypal-library/samples/classic/DoExpressCheckoutPayment.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => $domain . 'paypal/class/cancel.php', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'callback' => '', // URL to which the callback request from PayPal is sent. Must start with https:// for production. + 'callbacktimeout' => '', // An override for you to request more or less time to be able to process the callback request and response. Acceptable range for override is 1-6 seconds. If you specify greater than 6 PayPal will use default value of 3 seconds. + 'callbackversion' => '', // The version of the Instant Update API you're using. The default is the current version. + 'reqconfirmshipping' => '0', // The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal. This overrides anything in the account profile. Possible values are 1 or 0. + 'noshipping' => '1', // The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed. Maybe 1 or 0. + 'addroverride' => '', // The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal. This does not allow the customer to edit the address here. Must be 1 or 0. + 'localecode' => '', // Locale of pages displayed by PayPal during checkout. Should be a 2 character country code. You can retrive the country code by passing the country name into the class' GetCountryCode() function. + 'pagestyle' => '', // Sets the Custom Payment Page Style for payment pages associated with this button/link. + 'hdrimg' => '', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. + 'hdrbordercolor' => '', // Sets the border color around the header of the payment page. The border is a 2-pixel permiter around the header space. Default is black. + 'hdrbackcolor' => '', // Sets the background color for the header of the payment page. Default is white. + 'payflowcolor' => '', // Sets the background color for the payment page. Default is white. + 'skipdetails' => '', // This is a custom field not included in the PayPal documentation. It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not. See PayPal docs for more info. + 'email' => '', // Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal sign-in page. 127 char max. + 'solutiontype' => 'Sole', // Type of checkout flow. Must be Sole (express checkout for auctions) or Mark (normal express checkout) + 'landingpage' => 'Billing', // Type of PayPal page to display. Can be Billing or Login. If billing it shows a full credit card form. If Login it just shows the login screen. + 'channeltype' => '', // Type of channel. Must be Merchant (non-auction seller) or eBayItem (eBay auction) + 'giropaysuccessurl' => '', // The URL on the merchant site to redirect to after a successful giropay payment. Only use this field if you are using giropay or bank transfer payment methods in Germany. + 'giropaycancelurl' => '', // The URL on the merchant site to redirect to after a canceled giropay payment. Only use this field if you are using giropay or bank transfer methods in Germany. + 'banktxnpendingurl' => '', // The URL on the merchant site to transfer to after a bank transfter payment. Use this field only if you are using giropay or bank transfer methods in Germany. + 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. + 'customerservicenumber' => '555-555-5555', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. + 'giftmessageenable' => '1', // Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1 + 'giftreceiptenable' => '1', // Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1 + 'giftwrapenable' => '1', // Enable gift wrap widget on the PayPal Review page. Allowable values are 0 and 1. + 'giftwrapname' => 'Box with Ribbon', // Label for the gift wrap option such as "Box with ribbon". 25 char max. + 'giftwrapamount' => '2.50', // Amount charged for gift-wrap service. + 'buyeremailoptionenable' => '1', // Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1 + 'surveyquestion' => '', // Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present. 50 char max. + 'surveyenable' => '1', // Enable survey functionality. Allowable values are 0 and 1 + 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max. + 'buyerusername' => '', // The user name of the user at the marketplaces site. + 'buyerregistrationdate' => '2012-07-14T00:00:00Z', // Date when the user registered with the marketplace. + 'allowpushfunding' => '' // Whether the merchant can accept push funding. 0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding. +); // Basic array of survey choices. Nothing but the values should go in here. $SurveyChoices = array('Yes', 'No'); $Payments = array(); $Payment = array( - 'amt' => '100.00', // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - 'itemamt' => '80.00', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. - 'shippingamt' => '15.00', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. - 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount. If true, the total shipping insurance for this order must be a positive number. - 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. - 'taxamt' => '5.00', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. - 'desc' => 'This is a test order.', // Description of items on the order. 127 char max. - 'custom' => '', // Free-form field for your own use. 256 char max. - 'invnum' => '', // Your own invoice or tracking number. 127 char max. - 'notifyurl' => '', // URL for receiving Instant Payment Notifications - 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. - 'shiptostreet2' => '', // Second street address. 100 char max. - 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => '', // Phone number for shipping address. 20 char max. - 'notetext' => 'This is a test note before ever having left the web site.', // Note to the merchant. 255 char max. - 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. - 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. - 'paymentrequestid' => '', // A unique identifier of the specific payment request, which is required for parallel payments. - 'sellerpaypalaccountid' => '' // A unique identifier for the merchant. For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant. - ); + 'amt' => '100.00', // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'currencycode' => 'USD', // A three-character currency code. Default is USD. + 'itemamt' => '80.00', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. + 'shippingamt' => '15.00', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount. If true, the total shipping insurance for this order must be a positive number. + 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => '5.00', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'desc' => 'This is a test order.', // Description of items on the order. 127 char max. + 'custom' => '', // Free-form field for your own use. 256 char max. + 'invnum' => '', // Your own invoice or tracking number. 127 char max. + 'notifyurl' => '', // URL for receiving Instant Payment Notifications + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '', // Phone number for shipping address. 20 char max. + 'notetext' => 'This is a test note before ever having left the web site.', // Note to the merchant. 255 char max. + 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. + 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. + 'paymentrequestid' => '', // A unique identifier of the specific payment request, which is required for parallel payments. + 'sellerpaypalaccountid' => '' // A unique identifier for the merchant. For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant. +); $PaymentOrderItems = array(); $Item = array( - 'name' => 'Widget 123', // Item name. 127 char max. - 'desc' => 'Widget 123', // Item description. 127 char max. - 'amt' => '40.00', // Cost of item. - 'number' => '123', // Item number. 127 char max. - 'qty' => '1', // Item qty on order. Any positive integer. - 'taxamt' => '', // Item sales tax - 'itemurl' => 'http://www.angelleye.com/products/123.php', // URL for the item. - 'itemcategory' => '', // One of the following values: Digital, Physical - 'itemweightvalue' => '', // The weight value of the item. - 'itemweightunit' => '', // The weight unit of the item. - 'itemheightvalue' => '', // The height value of the item. - 'itemheightunit' => '', // The height unit of the item. - 'itemwidthvalue' => '', // The width value of the item. - 'itemwidthunit' => '', // The width unit of the item. - 'itemlengthvalue' => '', // The length value of the item. - 'itemlengthunit' => '', // The length unit of the item. - 'ebayitemnumber' => '', // Auction item number. - 'ebayitemauctiontxnid' => '', // Auction transaction ID number. - 'ebayitemorderid' => '', // Auction order ID number. - 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters - ); + 'name' => 'Widget 123', // Item name. 127 char max. + 'desc' => 'Widget 123', // Item description. 127 char max. + 'amt' => '40.00', // Cost of item. + 'number' => '123', // Item number. 127 char max. + 'qty' => '1', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => 'http://www.angelleye.com/products/123.php', // URL for the item. + 'itemcategory' => '', // One of the following values: Digital, Physical + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); array_push($PaymentOrderItems, $Item); $Item = array( - 'name' => 'Widget 456', // Item name. 127 char max. - 'desc' => 'Widget 456', // Item description. 127 char max. - 'amt' => '40.00', // Cost of item. - 'number' => '456', // Item number. 127 char max. - 'qty' => '1', // Item qty on order. Any positive integer. - 'taxamt' => '', // Item sales tax - 'itemurl' => 'http://www.angelleye.com/products/456.php', // URL for the item. - 'itemcategory' => 'Digital', // One of the following values: Digital, Physical - 'itemweightvalue' => '', // The weight value of the item. - 'itemweightunit' => '', // The weight unit of the item. - 'itemheightvalue' => '', // The height value of the item. - 'itemheightunit' => '', // The height unit of the item. - 'itemwidthvalue' => '', // The width value of the item. - 'itemwidthunit' => '', // The width unit of the item. - 'itemlengthvalue' => '', // The length value of the item. - 'itemlengthunit' => '', // The length unit of the item. - 'ebayitemnumber' => '', // Auction item number. - 'ebayitemauctiontxnid' => '', // Auction transaction ID number. - 'ebayitemorderid' => '', // Auction order ID number. - 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters - ); + 'name' => 'Widget 456', // Item name. 127 char max. + 'desc' => 'Widget 456', // Item description. 127 char max. + 'amt' => '40.00', // Cost of item. + 'number' => '456', // Item number. 127 char max. + 'qty' => '1', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => 'http://www.angelleye.com/products/456.php', // URL for the item. + 'itemcategory' => 'Digital', // One of the following values: Digital, Physical + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); array_push($PaymentOrderItems, $Item); $Payment['order_items'] = $PaymentOrderItems; array_push($Payments, $Payment); $BuyerDetails = array( - 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. Char max 255. - 'buyerusername' => '', // The username of the marketplace site. - 'buyerregistrationdate' => '' // The registration of the buyer with the marketplace. - ); + 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. Char max 255. + 'buyerusername' => '', // The username of the marketplace site. + 'buyerregistrationdate' => '' // The registration of the buyer with the marketplace. +); // For shipping options we create an array of all shipping choices similar to how order items works. $ShippingOptions = array(); $Option = array( - 'l_shippingoptionisdefault' => '', // Shipping option. Required if specifying the Callback URL. true or false. Must be only 1 default! - 'l_shippingoptionname' => '', // Shipping option name. Required if specifying the Callback URL. 50 character max. - 'l_shippingoptionlabel' => '', // Shipping option label. Required if specifying the Callback URL. 50 character max. - 'l_shippingoptionamount' => '' // Shipping option amount. Required if specifying the Callback URL. - ); + 'l_shippingoptionisdefault' => '', // Shipping option. Required if specifying the Callback URL. true or false. Must be only 1 default! + 'l_shippingoptionname' => '', // Shipping option name. Required if specifying the Callback URL. 50 character max. + 'l_shippingoptionlabel' => '', // Shipping option label. Required if specifying the Callback URL. 50 character max. + 'l_shippingoptionamount' => '' // Shipping option amount. Required if specifying the Callback URL. +); array_push($ShippingOptions, $Option); $BillingAgreements = array(); $Item = array( - 'l_billingtype' => 'MerchantInitiatedBilling', // Required. Type of billing agreement. For recurring payments it must be RecurringPayments. You can specify up to ten billing agreements. For reference transactions, this field must be either: MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource - 'l_billingagreementdescription' => 'Billing Agreement', // Required for recurring payments. Description of goods or services associated with the billing agreement. - 'l_paymenttype' => 'Any', // Specifies the type of PayPal payment you require for the billing agreement. Any or IntantOnly - 'l_billingagreementcustom' => '' // Custom annotation field for your own use. 256 char max. - ); + 'l_billingtype' => 'MerchantInitiatedBilling', // Required. Type of billing agreement. For recurring payments it must be RecurringPayments. You can specify up to ten billing agreements. For reference transactions, this field must be either: MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource + 'l_billingagreementdescription' => 'Billing Agreement', // Required for recurring payments. Description of goods or services associated with the billing agreement. + 'l_paymenttype' => 'Any', // Specifies the type of PayPal payment you require for the billing agreement. Any or IntantOnly + 'l_billingagreementcustom' => '' // Custom annotation field for your own use. 256 char max. +); array_push($BillingAgreements, $Item); $PayPalRequest = array( - 'SECFields' => $SECFields, - 'SurveyChoices' => $SurveyChoices, - 'BillingAgreements' => $BillingAgreements, - 'Payments' => $Payments - ); + 'SECFields' => $SECFields, + 'SurveyChoices' => $SurveyChoices, + 'BillingAgreements' => $BillingAgreements, + 'Payments' => $Payments +); -$_SESSION['SetExpressCheckoutResult'] = $PayPal -> SetExpressCheckout($PayPalRequest); +$_SESSION['SetExpressCheckoutResult'] = $PayPal->SetExpressCheckout($PayPalRequest); echo 'Click here to continue.

'; echo '
';
diff --git a/samples/rest/DoExpressCheckoutPayment.php b/samples/rest/DoExpressCheckoutPayment.php
new file mode 100644
index 00000000..5ee5117c
--- /dev/null
+++ b/samples/rest/DoExpressCheckoutPayment.php
@@ -0,0 +1,26 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$PayPalRequestedData = array(
+	'paymentID' => isset($_GET['paymentId']) ? $_GET['paymentId'] : '',
+	'token' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
+	'payerID' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
+);
+
+$ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
+
+echo '
';
+print_r($ExecuteResult);
\ No newline at end of file
diff --git a/samples/rest/SetExpressCheckout.php b/samples/rest/SetExpressCheckout.php
new file mode 100644
index 00000000..d85f4ec9
--- /dev/null
+++ b/samples/rest/SetExpressCheckout.php
@@ -0,0 +1,193 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APIVersion' => '97.0', 
+	'APISubject' => '',
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$SECFields = array(
+	'token' => '', 								// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'maxamt' => '200.00', 							// The expected maximum total amount the order will be, including S&H and sales tax.
+	'returnurl' => 'http://localhost:8888/paypal-library/samples/rest/DoExpressCheckoutPayment.php', 	// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
+	'cancelurl' => $domain . 'paypal/class/cancel.php', 			// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
+	'callback' => '', 							// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
+	'callbacktimeout' => '', 						// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
+	'callbackversion' => '', 						// The version of the Instant Update API you're using.  The default is the current version.							
+	'reqconfirmshipping' => '0', 						// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
+	'noshipping' => '1', 							// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
+	'addroverride' => '', 							// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
+	'localecode' => '', 							// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
+	'pagestyle' => '', 							// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
+	'hdrimg' => '', 							// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
+	'hdrbordercolor' => '', 						// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
+	'hdrbackcolor' => '', 							// Sets the background color for the header of the payment page.  Default is white.  
+	'payflowcolor' => '', 							// Sets the background color for the payment page.  Default is white.
+	'skipdetails' => '', 							// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
+	'email' => '', 								// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
+	'solutiontype' => 'Sole', 						// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
+	'landingpage' => 'Billing', 						// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
+	'channeltype' => '', 							// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
+	'giropaysuccessurl' => '', 						// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
+	'giropaycancelurl' => '', 						// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
+	'banktxnpendingurl' => '',  						// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
+	'brandname' => 'Angell EYE', 						// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
+	'customerservicenumber' => '555-555-5555', 				// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
+	'giftmessageenable' => '1', 						// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftreceiptenable' => '1', 						// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftwrapenable' => '1', 						// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
+	'giftwrapname' => 'Box with Ribbon', 					// Label for the gift wrap option such as "Box with ribbon".  25 char max.
+	'giftwrapamount' => '2.50', 						// Amount charged for gift-wrap service.
+	'buyeremailoptionenable' => '1', 					// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
+	'surveyquestion' => '', 						// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
+	'surveyenable' => '1', 							// Enable survey functionality. Allowable values are 0 and 1
+	'buyerid' => '', 							// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
+	'buyerusername' => '', 							// The user name of the user at the marketplaces site.
+	'buyerregistrationdate' => '2012-07-14T00:00:00Z',  			// Date when the user registered with the marketplace.
+	'allowpushfunding' => ''						// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
+);
+
+// Basic array of survey choices.  Nothing but the values should go in here.  
+$SurveyChoices = array('Yes', 'No');
+
+$Payments = array();
+$Payment = array(
+	'amt' => '100.00', 									// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+	'currencycode' => 'USD', 								// A three-character currency code.  Default is USD.
+	'itemamt' => '80.00', 									// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
+	'shippingamt' => '15.00', 								// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+	'insuranceoptionoffered' => '', 							// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+	'handlingamt' => '', 									// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+	'taxamt' => '5.00', 									// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
+	'desc' => 'This is a test order.', 							// Description of items on the order.  127 char max.
+	'custom' => '', 									// Free-form field for your own use.  256 char max.
+	'invnum' => '', 									// Your own invoice or tracking number.  127 char max.
+	'notifyurl' => '',  									// URL for receiving Instant Payment Notifications
+	'shiptoname' => '', 									// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 									// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 									// Second street address.  100 char max.
+	'shiptocity' => '', 									// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 									// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 									// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 									// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => '',  								// Phone number for shipping address.  20 char max.
+	'notetext' => 'This is a test note before ever having left the web site.', 		// Note to the merchant.  255 char max.  
+	'allowedpaymentmethod' => '', 								// The payment method type.  Specify the value InstantPaymentOnly.
+	'paymentaction' => 'Sale', 								// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
+	'paymentrequestid' => '',  								// A unique identifier of the specific payment request, which is required for parallel payments. 
+	'sellerpaypalaccountid' => ''								// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+);
+				
+$PaymentOrderItems = array();
+$Item = array(
+	'name' => 'Widget 123', 					// Item name. 127 char max.
+	'desc' => 'Widget 123', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '123', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/123.php',	// URL for the item.
+	'itemcategory' => '', 						// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Item = array(
+	'name' => 'Widget 456', 					// Item name. 127 char max.
+	'desc' => 'Widget 456', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '456', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/456.php', 	// URL for the item.
+	'itemcategory' => 'Digital', 					// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Payment['order_items'] = $PaymentOrderItems;
+array_push($Payments, $Payment);
+
+$BuyerDetails = array(
+	'buyerid' => '', 		// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
+	'buyerusername' => '', 		// The username of the marketplace site.
+	'buyerregistrationdate' => ''	// The registration of the buyer with the marketplace.
+);
+						
+// For shipping options we create an array of all shipping choices similar to how order items works.
+$ShippingOptions = array();
+$Option = array(
+	'l_shippingoptionisdefault' => '', 		// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
+	'l_shippingoptionname' => '', 			// Shipping option name.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionlabel' => '', 			// Shipping option label.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionamount' => '' 			// Shipping option amount.  Required if specifying the Callback URL.  
+);
+array_push($ShippingOptions, $Option);
+		
+$BillingAgreements = array();
+$Item = array(
+	'l_billingtype' => 'MerchantInitiatedBilling', 				// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
+	'l_billingagreementdescription' => 'Billing Agreement', 		// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
+	'l_paymenttype' => 'Any', 						// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
+	'l_billingagreementcustom' => ''					// Custom annotation field for your own use.  256 char max.
+);
+array_push($BillingAgreements, $Item);
+
+$PayPalRequest = array(
+	'SECFields' => $SECFields, 
+	'SurveyChoices' => $SurveyChoices, 
+	'BillingAgreements' => $BillingAgreements, 
+	'Payments' => $Payments
+);
+
+$PaymentResult = $PayPal->CreatePayment($PayPalRequest);
+
+// Save approval URL to session
+$_SESSION['PayPalPaymentID'] = $PaymentResult['RESPONSE']['id'];
+
+// Redirect user to PayPal approval URL
+$ApprovalUrl = '';
+foreach ($PaymentResult['RESPONSE']['links'] as $link) {
+    if ($link['rel'] === 'approval_url') {
+        $ApprovalUrl = $link['href'];
+        break;
+    }
+}
+
+echo 'Click here to continue.

'; +echo '
';
+print_r($PaymentResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 16a5252e..c2061ad5 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -504,6 +504,108 @@ private function getApprovalUrl($links)
         return null;
     }
 
+    public function CreatePayment($paymentData) {
+        $paymentsMappedData = [];
+
+        // Map basic payment info
+        $paymentsMappedData['intent'] = strtolower($paymentData['Payments'][0]['paymentaction'] ?? 'sale');
+        $paymentsMappedData['payer'] = [
+            'payment_method' => 'paypal'
+        ];
+
+        // Redirect URLs
+        $paymentsMappedData['redirect_urls'] = [
+            'return_url' => $paymentData['SECFields']['returnurl'] ?? '',
+            'cancel_url' => $paymentData['SECFields']['cancelurl'] ?? ''
+        ];
+
+        // Transaction
+        $transaction = [
+            'amount' => [
+                'total' => $paymentData['Payments'][0]['amt'] ?? '0.00',
+                'currency' => $paymentData['Payments'][0]['currencycode'] ?? 'USD',
+                'details' => [
+                    'subtotal' => $paymentData['Payments'][0]['itemamt'] ?? '0.00',
+                    'tax' => $paymentData['Payments'][0]['taxamt'] ?? '0.00',
+                    'shipping' => $paymentData['Payments'][0]['shippingamt'] ?? '0.00'
+                ]
+            ],
+            'description' => $paymentData['Payments'][0]['desc'] ?? '',
+            'item_list' => [
+                'items' => []
+            ]
+        ];
+
+        // Map order items
+        if (!empty($paymentData['Payments'][0]['order_items'])) {
+            foreach ($paymentData['Payments'][0]['order_items'] as $item) {
+                $transaction['item_list']['items'][] = [
+                    'name' => $item['name'] ?? '',
+                    'sku' => $item['number'] ?? '',
+                    'price' => $item['amt'] ?? '0.00',
+                    'currency' => $paymentData['Payments'][0]['currencycode'] ?? 'USD',
+                    'quantity' => $item['qty'] ?? 1
+                ];
+            }
+        }
+
+        $paymentsMappedData['transactions'][] = $transaction;
+        
+        $response = $this->makeRequest('/v1/payments/payment', 'POST', $paymentsMappedData);
+
+        $responseSimplified = [];
+
+        // Handle Response
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            $responseSimplified = array(
+                'SUCCESS' => true,
+                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        } else {
+            $responseSimplified = array(
+                'SUCCESS' => false,
+                'STATUSCODE' => $response['status_code'],
+                'ERRORS' => !empty($response['body']) ? $response['body'] : ['invalid_payment' => 'Payment execution failed'],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
+    public function ExecutePayment($paymentData) {
+        $data = [
+            'payer_id' => !empty($paymentData['payerID']) ? $paymentData['payerID'] : ''
+        ];
+
+        $paymentID = !empty($paymentData['paymentID']) ? $paymentData['paymentID'] : '';
+
+        $response = $this->makeRequest('/v1/payments/payment/' . $paymentID . '/execute', 'POST', $data);
+        
+        $responseSimplified = [];
+
+        // Handle Response
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            $responseSimplified = array(
+                'SUCCESS' => true,
+                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        } else {
+            $responseSimplified = array(
+                'SUCCESS' => false,
+                'STATUSCODE' => $response['status_code'],
+                'ERRORS' => !empty($response['body']) ? $response['body'] : ['invalid_payment' => 'Payment execution failed'],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/DoExpressCheckoutPayment.php b/templates/classic/DoExpressCheckoutPayment.php
index 0ecb8935..2aec2f53 100644
--- a/templates/classic/DoExpressCheckoutPayment.php
+++ b/templates/classic/DoExpressCheckoutPayment.php
@@ -5,110 +5,111 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
 $PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
 
 // Prepare request arrays
 $DECPFields = array(
-    'token' => '', 								// Required.  A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
-    'payerid' => '', 							// Required.  Unique PayPal customer id of the payer.  Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL.
-    'returnfmfdetails' => '', 					// Flag to indicate whether you want the results returned by Fraud Management Filters or not.  1 or 0.
-    'giftmessage' => '', 						// The gift message entered by the buyer on the PayPal Review page.  150 char max.
-    'giftreceiptenable' => '', 					// Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false.
-    'giftwrapname' => '', 						// The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer.
-    'giftwrapamount' => '', 					// The amount only if the gift option on the PayPal Review page was selected by the buyer.
-    'buyermarketingemail' => '', 				// The buyer email address opted in by the buyer on the PayPal Review page.
-    'skipbacreation' => '', 					// Merchant specified flag which indicates whether to create a billing agreement as part of DoExpressCheckout or not. This field is used for reference transactions during billing agreement creation. Merchants who offer a store account can control whether PayPal must create a billing agreement or if billing agreement creation should be skipped. Set the value of this field to true to skip the creation of a billing agreement ID.
-    'usesessionpaymentdetails' => '', 			// Merchant specified flag which indicates whether to use the payment details information provided in SetExpressCheckoutDetails or in DoExpressCheckoutPayment. Possible values are true, false, 1, 0. If this is set to true or 1, the payment details information would be used from what was passed in SetExpressCheckoutDetails. Any change in the paymentdetails passed in DoExpressCheckoutPayment will be ignored if this field is set to true.
-    'surveyquestion' => '', 					// The survey question on the PayPal Review page.  50 char max.
-    'surveychoiceselected' => '',  				// The survey response selected by the buyer on the PayPal Review page.  15 char max.
-    'allowedpaymentmethod' => '', 				// The payment method type. Specify the value InstantPaymentOnly.
-    'msgsubid' => '',                           // Unique ID passed for each API request to help prevent duplicate payments.  This ID is passed directly back in the response.
+	'token' => '', 					// Required.  A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'payerid' => '', 				// Required.  Unique PayPal customer id of the payer.  Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL.
+	'returnfmfdetails' => '', 			// Flag to indicate whether you want the results returned by Fraud Management Filters or not.  1 or 0.
+	'giftmessage' => '', 				// The gift message entered by the buyer on the PayPal Review page.  150 char max.
+	'giftreceiptenable' => '', 			// Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false.
+	'giftwrapname' => '', 				// The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer.
+	'giftwrapamount' => '', 			// The amount only if the gift option on the PayPal Review page was selected by the buyer.
+	'buyermarketingemail' => '', 			// The buyer email address opted in by the buyer on the PayPal Review page.
+	'skipbacreation' => '', 			// Merchant specified flag which indicates whether to create a billing agreement as part of DoExpressCheckout or not. This field is used for reference transactions during billing agreement creation. Merchants who offer a store account can control whether PayPal must create a billing agreement or if billing agreement creation should be skipped. Set the value of this field to true to skip the creation of a billing agreement ID.
+	'usesessionpaymentdetails' => '', 		// Merchant specified flag which indicates whether to use the payment details information provided in SetExpressCheckoutDetails or in DoExpressCheckoutPayment. Possible values are true, false, 1, 0. If this is set to true or 1, the payment details information would be used from what was passed in SetExpressCheckoutDetails. Any change in the paymentdetails passed in DoExpressCheckoutPayment will be ignored if this field is set to true.
+	'surveyquestion' => '', 			// The survey question on the PayPal Review page.  50 char max.
+	'surveychoiceselected' => '',  			// The survey response selected by the buyer on the PayPal Review page.  15 char max.
+	'allowedpaymentmethod' => '', 			// The payment method type. Specify the value InstantPaymentOnly.
+	'msgsubid' => '',                         	// Unique ID passed for each API request to help prevent duplicate payments.  This ID is passed directly back in the response.
 );
 						
 $Payments = array();
 $Payment = array(
-				'amt' => '', 							// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
-				'bucketcategorytype' => '', 			// The category of a payment. It is one of the following values:  1 - International shipping   2 - Local delivery
-				'currencycode' => '', 					// A three-character currency code.  Default is USD.
-				'itemamt' => '', 						// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
-				'shippingamt' => '', 					// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
-				'shippingdiscamt' => '', 				// Total shipping discount for this order, specified as a negative number.
-				'insuranceoptionoffered' => '', 		// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
-				'handlingamt' => '', 					// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
-				'taxamt' => '', 						// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
-				'desc' => '', 							// Description of items on the order.  127 char max.
-				'custom' => '', 						// Free-form field for your own use.  256 char max.
-				'invnum' => '', 						// Your own invoice or tracking number.  127 char max.
-				'notifyurl' => '', 						// URL for receiving Instant Payment Notifications
-				'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-				'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-				'shiptostreet2' => '', 					// Second street address.  100 char max.
-				'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-				'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-				'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-				'shiptocountrycode' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
-				'shiptophonenum' => '',  				// Phone number for shipping address.  20 char max.
-				'notetext' => '', 						// Note to the merchant.  255 char max.  
-				'allowedpaymentmethod' => '', 			// The payment method type.  Specify the value InstantPaymentOnly.
-				'paymentaction' => '', 					// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
-				'paymentrequestid' => '',  				// A unique identifier of the specific payment request, which is required for parallel payments. 
-				'sellerpaypalaccountid' => '', 			// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
-				'sellerid' => '', 						// The unique non-changing identifer for the seller at the marketplace site.  This ID is not displayed.
-				'sellerusername' => '', 				// The current name of the seller or business at the marketplace site.  This name may be shown to the buyer.
-				'sellerregistrationdate' => '', 		// Date when the seller registered at the marketplace site.
-				'softdescriptor' => ''					// A per transaction description of the payment that is passed to the buyer's credit card statement.
-				);
+	'amt' => '', 					// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+	'bucketcategorytype' => '', 			// The category of a payment. It is one of the following values:  1 - International shipping   2 - Local delivery
+	'currencycode' => '', 				// A three-character currency code.  Default is USD.
+	'itemamt' => '', 				// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
+	'shippingamt' => '', 				// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+	'shippingdiscamt' => '', 			// Total shipping discount for this order, specified as a negative number.
+	'insuranceoptionoffered' => '', 		// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+	'handlingamt' => '', 				// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+	'taxamt' => '', 				// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
+	'desc' => '', 					// Description of items on the order.  127 char max.
+	'custom' => '', 				// Free-form field for your own use.  256 char max.
+	'invnum' => '', 				// Your own invoice or tracking number.  127 char max.
+	'notifyurl' => '', 				// URL for receiving Instant Payment Notifications
+	'shiptoname' => '', 				// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 				// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 				// Second street address.  100 char max.
+	'shiptocity' => '', 				// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 				// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 				// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountrycode' => '', 			// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => '',  			// Phone number for shipping address.  20 char max.
+	'notetext' => '', 				// Note to the merchant.  255 char max.  
+	'allowedpaymentmethod' => '', 			// The payment method type.  Specify the value InstantPaymentOnly.
+	'paymentaction' => '', 				// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
+	'paymentrequestid' => '',  			// A unique identifier of the specific payment request, which is required for parallel payments. 
+	'sellerpaypalaccountid' => '', 			// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+	'sellerid' => '', 				// The unique non-changing identifer for the seller at the marketplace site.  This ID is not displayed.
+	'sellerusername' => '', 			// The current name of the seller or business at the marketplace site.  This name may be shown to the buyer.
+	'sellerregistrationdate' => '', 		// Date when the seller registered at the marketplace site.
+	'softdescriptor' => ''				// A per transaction description of the payment that is passed to the buyer's credit card statement.
+);
 
 // The $PaymentOrderItems array may contain multiple $Item arrays within it.
 $PaymentOrderItems = array();
 $Item = array(
-			'name' => '', 								// Item name. 127 char max.
-			'desc' => '', 								// Item description. 127 char max.
-			'amt' => '', 								// Cost of item.
-			'number' => '', 							// Item number.  127 char max.
-			'qty' => '', 								// Item qty on order.  Any positive integer.
-			'taxamt' => '', 							// Item sales tax
-			'itemurl' => '', 							// URL for the item.
-			'itemcategory' => '', 						// One of the following values:  Digital, Physical
-			'itemweightvalue' => '', 					// The weight value of the item.
-			'itemweightunit' => '', 					// The weight unit of the item.
-			'itemheightvalue' => '', 					// The height value of the item.
-			'itemheightunit' => '', 					// The height unit of the item.
-			'itemwidthvalue' => '', 					// The width value of the item.
-			'itemwidthunit' => '', 						// The width unit of the item.
-			'itemlengthvalue' => '', 					// The length value of the item.
-			'itemlengthunit' => '',  					// The length unit of the item.
-			'ebayitemnumber' => '', 					// Auction item number.  
-			'ebayitemauctiontxnid' => '', 				// Auction transaction ID number.  
-			'ebayitemorderid' => '',  					// Auction order ID number.
-			'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
-			);
+	'name' => '', 				// Item name. 127 char max.
+	'desc' => '', 				// Item description. 127 char max.
+	'amt' => '', 				// Cost of item.
+	'number' => '', 			// Item number.  127 char max.
+	'qty' => '', 				// Item qty on order.  Any positive integer.
+	'taxamt' => '', 			// Item sales tax
+	'itemurl' => '', 			// URL for the item.
+	'itemcategory' => '', 			// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 		// The weight value of the item.
+	'itemweightunit' => '', 		// The weight unit of the item.
+	'itemheightvalue' => '', 		// The height value of the item.
+	'itemheightunit' => '', 		// The height unit of the item.
+	'itemwidthvalue' => '', 		// The width value of the item.
+	'itemwidthunit' => '', 			// The width unit of the item.
+	'itemlengthvalue' => '', 		// The length value of the item.
+	'itemlengthunit' => '',  		// The length unit of the item.
+	'ebayitemnumber' => '', 		// Auction item number.  
+	'ebayitemauctiontxnid' => '', 		// Auction transaction ID number.  
+	'ebayitemorderid' => '',  		// Auction order ID number.
+	'ebayitemcartid' => ''			// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
 array_push($PaymentOrderItems, $Item);
 $Payment['order_items'] = $PaymentOrderItems;				
 
 // The $PaymentRedeemedOffers array may contain multiple $RedeemedOffer arrays within it.
 $PaymentRedeemedOffers = array();
 $RedeemedOffer = array(
-    'redeemedoffername' => '', 						    // The name of the buyer's wallet item offer redeemed in this transaction, such as, a merchant coupon or a loyalty program card.
-    'redeemedofferdescription' => '',                    // Description of the offer redeemed in this transaction, such as, a merchant coupon or a loyalty program.  This is returned in GetExpressCheckoutDetails as WALLETDESCRIPTIONn
-    'redeemedofferamount' => '',                         // Amount of the offer redeemed in this transaction
-    'redeemedoffertype' => '',                           // The type of the offer redeemed in this transaction.  This is returned in GetExpressCheckoutDetails as WALLETTYPEn
-    'redeemedofferid' => '',                             // Unique ID of the offer redeemed in this transaction or the buyer's loyalty card account number.  This is returned in GetExpresscheckoutDetails as WALLETIDn
-    'redeemedofferpointsaccrued' => '',                  // The number of loyalty points accrued in this transaction.
-    'cummulativepointsname' => '',          // The name of the loyalty points program in which the buyer earned points in this transaction.
-    'cummulativepointsdescription' => '',   // Description of the loyalty points program.
-    'cummulativepointstype' => '',          // Type of discount or loyalty p rogram.  Values:  LOYALTY_CARD
-    'cummulativepointsid' => '',            // Unique ID of the buyer's loyalty points account.
-    'cummulativepointsaccrued' => '',       // The cummulative number of loyalty points the buyer has accrued.
+    'redeemedoffername' => '', 			// The name of the buyer's wallet item offer redeemed in this transaction, such as, a merchant coupon or a loyalty program card.
+    'redeemedofferdescription' => '',           // Description of the offer redeemed in this transaction, such as, a merchant coupon or a loyalty program.  This is returned in GetExpressCheckoutDetails as WALLETDESCRIPTIONn
+    'redeemedofferamount' => '',                // Amount of the offer redeemed in this transaction
+    'redeemedoffertype' => '',                  // The type of the offer redeemed in this transaction.  This is returned in GetExpressCheckoutDetails as WALLETTYPEn
+    'redeemedofferid' => '',                    // Unique ID of the offer redeemed in this transaction or the buyer's loyalty card account number.  This is returned in GetExpresscheckoutDetails as WALLETIDn
+    'redeemedofferpointsaccrued' => '',         // The number of loyalty points accrued in this transaction.
+    'cummulativepointsname' => '',          	// The name of the loyalty points program in which the buyer earned points in this transaction.
+    'cummulativepointsdescription' => '',   	// Description of the loyalty points program.
+    'cummulativepointstype' => '',          	// Type of discount or loyalty p rogram.  Values:  LOYALTY_CARD
+    'cummulativepointsid' => '',            	// Unique ID of the buyer's loyalty points account.
+    'cummulativepointsaccrued' => '',       	// The cummulative number of loyalty points the buyer has accrued.
 );
 array_push($PaymentRedeemedOffers, $RedeemedOffer);
 $Payment['redeemed_offers'] = $PaymentRedeemedOffers;
@@ -116,8 +117,8 @@
 // You may include up to 16 $MerchantDataVar arrays within the $MerchantDataVars array.
 $MerchantDataVars = array();
 $MerchantDataVar = array(
-    'merchantdatakey' => '',                            // The key name of a merchant data key-value pair passed with the transaction.
-    'merchantdatavalue' => '',                          // The value of the data passed for the key.
+    'merchantdatakey' => '',            // The key name of a merchant data key-value pair passed with the transaction.
+    'merchantdatavalue' => '',          // The value of the data passed for the key.
 );
 array_push($MerchantDataVars, $MerchantDataVar);
 
@@ -127,18 +128,18 @@
 array_push($Payments, $Payment);
 
 $UserSelectedOptions = array(
-							 'shippingcalculationmode' => '', 	// Describes how the options that were presented to the user were determined.  values are:  API - Callback   or   API - Flatrate.
-							 'insuranceoptionselected' => '', 	// The Yes/No option that you chose for insurance.
-							 'shippingoptionisdefault' => '', 	// Is true if the buyer chose the default shipping option.  
-							 'shippingoptionamount' => '', 		// The shipping amount that was chosen by the buyer.
-							 'shippingoptionname' => '', 		// Is true if the buyer chose the default shipping option...??  Maybe this is supposed to show the name..??
-							 );
+	'shippingcalculationmode' => '', 	// Describes how the options that were presented to the user were determined.  values are:  API - Callback   or   API - Flatrate.
+	'insuranceoptionselected' => '', 	// The Yes/No option that you chose for insurance.
+	'shippingoptionisdefault' => '', 	// Is true if the buyer chose the default shipping option.  
+	'shippingoptionamount' => '', 		// The shipping amount that was chosen by the buyer.
+	'shippingoptionname' => '', 		// Is true if the buyer chose the default shipping option...??  Maybe this is supposed to show the name..??
+);
 							 
 $PayPalRequestData = array(
-					   'DECPFields' => $DECPFields, 
-					   'Payments' => $Payments, 
-					   'UserSelectedOptions' => $UserSelectedOptions
-					   );
+	'DECPFields' => $DECPFields, 
+	'Payments' => $Payments, 
+	'UserSelectedOptions' => $UserSelectedOptions
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData);
diff --git a/templates/classic/SetExpressCheckout.php b/templates/classic/SetExpressCheckout.php
index 1cb13751..abff9d71 100644
--- a/templates/classic/SetExpressCheckout.php
+++ b/templates/classic/SetExpressCheckout.php
@@ -5,166 +5,167 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $SECFields = array(
-					'token' => '', 								// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
-					'maxamt' => '', 							// The expected maximum total amount the order will be, including S&H and sales tax.
-					'returnurl' => '', 							// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
-					'cancelurl' => '', 							// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
-					'callback' => '', 							// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
-					'callbacktimeout' => '', 					// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
-					'callbackversion' => '', 					// The version of the Instant Update API you're using.  The default is the current version.							
-					'reqconfirmshipping' => '', 				// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
-					'noshipping' => '', 						// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
-					'addroverride' => '', 						// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
-					'localecode' => '', 						// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
-					'pagestyle' => '', 							// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
-					'hdrimg' => '', 							// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
-					'hdrbordercolor' => '', 					// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
-					'hdrbackcolor' => '', 						// Sets the background color for the header of the payment page.  Default is white.  
-					'payflowcolor' => '', 						// Sets the background color for the payment page.  Default is white.
-					'cartbordercolor' => '', 					// The HTML hex code for your principal identifying color.  PayPal blends your color to white in a gradient fill that borders the cart review area of the PayPal checkout user interface.  6 single-byte hexadecimal chars. that represent an HTML hex code for a color.
-					'logoimg' => '', 							// A URL to your logo image.  Formats:  .gif, .jpg, .png.  190x60.  PayPal places your logo image at the top of the cart review area.  This logo needs to be stored on a https:// server.
-					'skipdetails' => '', 						// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
-					'email' => '', 								// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
-					'solutiontype' => '', 						// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
-					'landingpage' => '', 						// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
-					'channeltype' => '', 						// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
-					'giropaysuccessurl' => '', 					// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
-					'giropaycancelurl' => '', 					// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
-					'banktxnpendingurl' => '',  				// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
-					'brandname' => '', 							// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
-					'customerservicenumber' => '', 				// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
-					'giftmessageenable' => '', 					// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
-					'giftreceiptenable' => '', 					// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
-					'giftwrapenable' => '', 					// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
-					'giftwrapname' => '', 						// Label for the gift wrap option such as "Box with ribbon".  25 char max.
-					'giftwrapamount' => '', 					// Amount charged for gift-wrap service.
-					'buyeremailoptionenable' => '', 			// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
-					'surveyquestion' => '', 					// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
-					'surveyenable' => '', 						// Enable survey functionality. Allowable values are 0 and 1
-					'totaltype' => '', 							// Enables display of "estimated total" instead of "total" in the cart review area.  Values are:  Total, EstimatedTotal
-					'notetobuyer' => '', 						// Displays a note to buyers in the cart review area below the total amount.  Use the note to tell buyers about items in the cart, such as your return policy or that the total excludes shipping and handling.  127 char max.
-					'buyerid' => '', 							// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
-					'buyerusername' => '', 						// The user name of the user at the marketplaces site.
-					'buyerregistrationdate' => '',  			// Date when the user registered with the marketplace.
-					'allowpushfunding' => '', 					// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
-					'userselectedfundingsource' => '', 			// This element could be used to specify the preferred funding option for a guest user.  However, the LANDINGPAGE element must also be set to Billing.  Otherwise, it is ignored.  Values:  BML, ChinaUnionPay, CreditCard, ELV, Finance, QIWI
-					'taxidtype' => '', 							// The buyer's tax ID type.  This field is required for Brazil and used for Brazil only.  Values:  BR_CPF for individuals and BR_CNPJ for businesses.
-					'taxid' => ''								// The buyer's tax ID.  This field is required for Brazil and used for Brazil only.  The tax ID is 11 single-byte characters for individutals and 14 single-byte characters for businesses.
-				);
+	'token' => '', 				// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'maxamt' => '', 			// The expected maximum total amount the order will be, including S&H and sales tax.
+	'returnurl' => '', 			// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
+	'cancelurl' => '', 			// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
+	'callback' => '', 			// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
+	'callbacktimeout' => '', 		// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
+	'callbackversion' => '', 		// The version of the Instant Update API you're using.  The default is the current version.							
+	'reqconfirmshipping' => '', 		// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
+	'noshipping' => '', 			// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
+	'addroverride' => '', 			// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
+	'localecode' => '', 			// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
+	'pagestyle' => '', 			// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
+	'hdrimg' => '', 			// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
+	'hdrbordercolor' => '', 		// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
+	'hdrbackcolor' => '', 			// Sets the background color for the header of the payment page.  Default is white.  
+	'payflowcolor' => '', 			// Sets the background color for the payment page.  Default is white.
+	'cartbordercolor' => '', 		// The HTML hex code for your principal identifying color.  PayPal blends your color to white in a gradient fill that borders the cart review area of the PayPal checkout user interface.  6 single-byte hexadecimal chars. that represent an HTML hex code for a color.
+	'logoimg' => '', 			// A URL to your logo image.  Formats:  .gif, .jpg, .png.  190x60.  PayPal places your logo image at the top of the cart review area.  This logo needs to be stored on a https:// server.
+	'skipdetails' => '', 			// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
+	'email' => '', 				// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
+	'solutiontype' => '', 			// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
+	'landingpage' => '', 			// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
+	'channeltype' => '', 			// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
+	'giropaysuccessurl' => '', 		// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
+	'giropaycancelurl' => '', 		// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
+	'banktxnpendingurl' => '',  		// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
+	'brandname' => '', 			// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
+	'customerservicenumber' => '', 		// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
+	'giftmessageenable' => '', 		// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftreceiptenable' => '', 		// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftwrapenable' => '', 		// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
+	'giftwrapname' => '', 			// Label for the gift wrap option such as "Box with ribbon".  25 char max.
+	'giftwrapamount' => '', 		// Amount charged for gift-wrap service.
+	'buyeremailoptionenable' => '', 	// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
+	'surveyquestion' => '', 		// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
+	'surveyenable' => '', 			// Enable survey functionality. Allowable values are 0 and 1
+	'totaltype' => '', 			// Enables display of "estimated total" instead of "total" in the cart review area.  Values are:  Total, EstimatedTotal
+	'notetobuyer' => '', 			// Displays a note to buyers in the cart review area below the total amount.  Use the note to tell buyers about items in the cart, such as your return policy or that the total excludes shipping and handling.  127 char max.
+	'buyerid' => '', 			// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
+	'buyerusername' => '', 			// The user name of the user at the marketplaces site.
+	'buyerregistrationdate' => '',  	// Date when the user registered with the marketplace.
+	'allowpushfunding' => '', 		// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
+	'userselectedfundingsource' => '', 	// This element could be used to specify the preferred funding option for a guest user.  However, the LANDINGPAGE element must also be set to Billing.  Otherwise, it is ignored.  Values:  BML, ChinaUnionPay, CreditCard, ELV, Finance, QIWI
+	'taxidtype' => '', 			// The buyer's tax ID type.  This field is required for Brazil and used for Brazil only.  Values:  BR_CPF for individuals and BR_CNPJ for businesses.
+	'taxid' => ''				// The buyer's tax ID.  This field is required for Brazil and used for Brazil only.  The tax ID is 11 single-byte characters for individutals and 14 single-byte characters for businesses.
+);
 
 // Basic array of survey choices.  Nothing but the values should go in here.  
 $SurveyChoices = array('Choice 1', 'Choice2', 'Choice3', 'etc');
 
 $Payments = array();
 $Payment = array(
-    'amt' => '', 							// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
-    'currencycode' => '', 					// A three-character currency code.  Default is USD.
-    'itemamt' => '', 						// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
-    'shippingamt' => '', 					// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
-    'shipdiscamt' => '', 					// Shipping discount for this order, specified as a negative number.
-    'insuranceamt' => '', 					// Total shipping insurance costs for this order.
-    'insuranceoptionoffered' => '', 		// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
-    'handlingamt' => '', 					// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
-    'taxamt' => '', 						// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
-    'desc' => '', 							// Description of items on the order.  127 char max.
-    'custom' => '', 						// Free-form field for your own use.  256 char max.
-    'invnum' => '', 						// Your own invoice or tracking number.  127 char max.
-    'notifyurl' => '', 						// URL for receiving Instant Payment Notifications
-    'multishipping' => '', 					// The value 1 indicates that this payment is associated with multiple shipping addresses.
-    'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-    'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-    'shiptostreet2' => '', 					// Second street address.  100 char max.
-    'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-    'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-    'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-    'shiptocountrycode' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
-    'shiptophonenum' => '',  				// Phone number for shipping address.  20 char max.
-    'notetext' => '', 						// Note to the merchant.  255 char max.
-    'allowedpaymentmethod' => '', 			// The payment method type.  Specify the value InstantPaymentOnly.
-    'paymentaction' => '', 					// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order.
-    'paymentrequestid' => '',  				// A unique identifier of the specific payment request, which is required for parallel payments.
-    'sellerpaypalaccountid' => '',			// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
-    'transactionid' => '',					// Transaction ID number of the transaction that was created.  You can specify up to 10 payments.
-    'bucketcategorytype' => '',             // The category of a payment.  Values are:  1 - International shipping, 2 - Local delivery, 3 - BOPIS (Buy online pick-up in store), 4 - PUDO (Pick up drop off)
-    'location_type' => '',                  // The type of merchant location.  Set this field if the items purchased will not be shipped, such as, BOPIS transactions.  Values are: 1 - Consumer, 2 - Store, for BOPIS transactions, 3 - PUDO
-    'location_id' => '',                    // The Location ID specified by the merchant for BOPIS or PUDO transactions.
+    'amt' => '', 			// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+    'currencycode' => '', 		// A three-character currency code.  Default is USD.
+    'itemamt' => '', 			// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
+    'shippingamt' => '', 		// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+    'shipdiscamt' => '', 		// Shipping discount for this order, specified as a negative number.
+    'insuranceamt' => '', 		// Total shipping insurance costs for this order.
+    'insuranceoptionoffered' => '', 	// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+    'handlingamt' => '', 		// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+    'taxamt' => '', 			// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
+    'desc' => '', 			// Description of items on the order.  127 char max.
+    'custom' => '', 			// Free-form field for your own use.  256 char max.
+    'invnum' => '', 			// Your own invoice or tracking number.  127 char max.
+    'notifyurl' => '', 			// URL for receiving Instant Payment Notifications
+    'multishipping' => '', 		// The value 1 indicates that this payment is associated with multiple shipping addresses.
+    'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+    'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+    'shiptostreet2' => '', 		// Second street address.  100 char max.
+    'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+    'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+    'shiptozip' => '', 			// Required if shipping is included.  Postal code of shipping address.  20 char max.
+    'shiptocountrycode' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+    'shiptophonenum' => '',  		// Phone number for shipping address.  20 char max.
+    'notetext' => '', 			// Note to the merchant.  255 char max.
+    'allowedpaymentmethod' => '', 	// The payment method type.  Specify the value InstantPaymentOnly.
+    'paymentaction' => '', 		// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order.
+    'paymentrequestid' => '',  		// A unique identifier of the specific payment request, which is required for parallel payments.
+    'sellerpaypalaccountid' => '',	// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+    'transactionid' => '',		// Transaction ID number of the transaction that was created.  You can specify up to 10 payments.
+    'bucketcategorytype' => '',         // The category of a payment.  Values are:  1 - International shipping, 2 - Local delivery, 3 - BOPIS (Buy online pick-up in store), 4 - PUDO (Pick up drop off)
+    'location_type' => '',              // The type of merchant location.  Set this field if the items purchased will not be shipped, such as, BOPIS transactions.  Values are: 1 - Consumer, 2 - Store, for BOPIS transactions, 3 - PUDO
+    'location_id' => '',                // The Location ID specified by the merchant for BOPIS or PUDO transactions.
 );
 				
 $PaymentOrderItems = array();
 $Item = array(
-			'name' => '', 								// Item name. 127 char max.
-			'desc' => '', 								// Item description. 127 char max.
-			'amt' => '', 								// Cost of item.
-			'number' => '', 							// Item number.  127 char max.
-			'qty' => '', 								// Item qty on order.  Any positive integer.
-			'taxamt' => '', 							// Item sales tax
-			'itemurl' => '', 							// URL for the item.
-			'itemcategory' => '', 						// One of the following values:  Digital, Physical
-			'itemweightvalue' => '', 					// The weight value of the item.
-			'itemweightunit' => '', 					// The weight unit of the item.
-			'itemheightvalue' => '', 					// The height value of the item.
-			'itemheightunit' => '', 					// The height unit of the item.
-			'itemwidthvalue' => '', 					// The width value of the item.
-			'itemwidthunit' => '', 						// The width unit of the item.
-			'itemlengthvalue' => '', 					// The length value of the item.
-			'itemlengthunit' => '',  					// The length unit of the item.
-			'ebayitemnumber' => '', 					// Auction item number.  
-			'ebayitemauctiontxnid' => '', 				// Auction transaction ID number.  
-			'ebayitemorderid' => '',  					// Auction order ID number.
-			'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
-			);
+	'name' => '', 				// Item name. 127 char max.
+	'desc' => '', 				// Item description. 127 char max.
+	'amt' => '', 				// Cost of item.
+	'number' => '', 			// Item number.  127 char max.
+	'qty' => '', 				// Item qty on order.  Any positive integer.
+	'taxamt' => '', 			// Item sales tax
+	'itemurl' => '', 			// URL for the item.
+	'itemcategory' => '', 			// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 		// The weight value of the item.
+	'itemweightunit' => '', 		// The weight unit of the item.
+	'itemheightvalue' => '', 		// The height value of the item.
+	'itemheightunit' => '', 		// The height unit of the item.
+	'itemwidthvalue' => '', 		// The width value of the item.
+	'itemwidthunit' => '', 			// The width unit of the item.
+	'itemlengthvalue' => '', 		// The length value of the item.
+	'itemlengthunit' => '',  		// The length unit of the item.
+	'ebayitemnumber' => '', 		// Auction item number.  
+	'ebayitemauctiontxnid' => '', 		// Auction transaction ID number.  
+	'ebayitemorderid' => '',  		// Auction order ID number.
+	'ebayitemcartid' => ''			// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
 array_push($PaymentOrderItems, $Item);
 $Payment['order_items'] = $PaymentOrderItems;
 
 array_push($Payments, $Payment);
 
 $BuyerDetails = array(
-						'buyerid' => '', 				// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
-						'buyerusername' => '', 			// The username of the marketplace site.
-						'buyerregistrationdate' => ''	// The registration of the buyer with the marketplace.
-						);
+	'buyerid' => '', 			// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
+	'buyerusername' => '', 			// The username of the marketplace site.
+	'buyerregistrationdate' => ''		// The registration of the buyer with the marketplace.
+);
 						
 // For shipping options we create an array of all shipping choices similar to how order items works.
 $ShippingOptions = array();
 $Option = array(
-				'l_shippingoptionisdefault' => '', 				// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
-				'l_shippingoptionname' => '', 					// Shipping option name.  Required if specifying the Callback URL.  50 character max.
-				'l_shippingoptionlabel' => '', 					// Shipping option label.  Required if specifying the Callback URL.  50 character max.
-				'l_shippingoptionamount' => '' 					// Shipping option amount.  Required if specifying the Callback URL.  
-				);
+	'l_shippingoptionisdefault' => '', 	// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
+	'l_shippingoptionname' => '', 		// Shipping option name.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionlabel' => '', 		// Shipping option label.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionamount' => '' 		// Shipping option amount.  Required if specifying the Callback URL.  
+);
 array_push($ShippingOptions, $Option);
 		
 $BillingAgreements = array();
 $Item = array(
-			  'l_billingtype' => '', 							// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
-			  'l_billingagreementdescription' => '', 			// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
-			  'l_paymenttype' => '', 							// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
-			  'l_billingagreementcustom' => ''					// Custom annotation field for your own use.  256 char max.
-			  );
+	'l_billingtype' => '', 				// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
+	'l_billingagreementdescription' => '', 		// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
+	'l_paymenttype' => '', 				// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
+	'l_billingagreementcustom' => ''		// Custom annotation field for your own use.  256 char max.
+);
 
 array_push($BillingAgreements, $Item);
 
 $PayPalRequestData = array(
-					   'SECFields' => $SECFields, 
-					   'SurveyChoices' => $SurveyChoices, 
-					   'Payments' => $Payments, 
-					   'BuyerDetails' => $BuyerDetails, 
-					   'ShippingOptions' => $ShippingOptions, 
-					   'BillingAgreements' => $BillingAgreements
-					   );
+	'SECFields' => $SECFields, 
+	'SurveyChoices' => $SurveyChoices, 
+	'Payments' => $Payments, 
+	'BuyerDetails' => $BuyerDetails, 
+	'ShippingOptions' => $ShippingOptions, 
+	'BillingAgreements' => $BillingAgreements
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData);
diff --git a/templates/rest/DoExpressCheckoutPayment.php b/templates/rest/DoExpressCheckoutPayment.php
new file mode 100644
index 00000000..8cef089b
--- /dev/null
+++ b/templates/rest/DoExpressCheckoutPayment.php
@@ -0,0 +1,29 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$PayPalRequestedData = array(
+	'paymentID' => isset($_GET['paymentId']) ? $_GET['paymentId'] : '',
+	'token' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
+	'payerID' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
+);
+
+$ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
+
+echo '
';
+print_r($ExecuteResult);
\ No newline at end of file
diff --git a/templates/rest/SetExpressCheckout.php b/templates/rest/SetExpressCheckout.php
new file mode 100644
index 00000000..ff488bb1
--- /dev/null
+++ b/templates/rest/SetExpressCheckout.php
@@ -0,0 +1,185 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$SECFields = array(
+	'token' => '', 				// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'maxamt' => '', 			// The expected maximum total amount the order will be, including S&H and sales tax.
+	'returnurl' => '', 			// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
+	'cancelurl' => '', 			// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
+	'callback' => '', 			// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
+	'callbacktimeout' => '', 		// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
+	'callbackversion' => '', 		// The version of the Instant Update API you're using.  The default is the current version.							
+	'reqconfirmshipping' => '', 		// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
+	'noshipping' => '', 			// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
+	'addroverride' => '', 			// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
+	'localecode' => '', 			// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
+	'pagestyle' => '', 			// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
+	'hdrimg' => '', 			// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
+	'hdrbordercolor' => '', 		// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
+	'hdrbackcolor' => '', 			// Sets the background color for the header of the payment page.  Default is white.  
+	'payflowcolor' => '', 			// Sets the background color for the payment page.  Default is white.
+	'cartbordercolor' => '', 		// The HTML hex code for your principal identifying color.  PayPal blends your color to white in a gradient fill that borders the cart review area of the PayPal checkout user interface.  6 single-byte hexadecimal chars. that represent an HTML hex code for a color.
+	'logoimg' => '', 			// A URL to your logo image.  Formats:  .gif, .jpg, .png.  190x60.  PayPal places your logo image at the top of the cart review area.  This logo needs to be stored on a https:// server.
+	'skipdetails' => '', 			// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
+	'email' => '', 				// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
+	'solutiontype' => '', 			// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
+	'landingpage' => '', 			// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
+	'channeltype' => '', 			// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
+	'giropaysuccessurl' => '', 		// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
+	'giropaycancelurl' => '', 		// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
+	'banktxnpendingurl' => '',  		// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
+	'brandname' => '', 			// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
+	'customerservicenumber' => '', 		// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
+	'giftmessageenable' => '', 		// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftreceiptenable' => '', 		// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftwrapenable' => '', 		// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
+	'giftwrapname' => '', 			// Label for the gift wrap option such as "Box with ribbon".  25 char max.
+	'giftwrapamount' => '', 		// Amount charged for gift-wrap service.
+	'buyeremailoptionenable' => '', 	// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
+	'surveyquestion' => '', 		// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
+	'surveyenable' => '', 			// Enable survey functionality. Allowable values are 0 and 1
+	'totaltype' => '', 			// Enables display of "estimated total" instead of "total" in the cart review area.  Values are:  Total, EstimatedTotal
+	'notetobuyer' => '', 			// Displays a note to buyers in the cart review area below the total amount.  Use the note to tell buyers about items in the cart, such as your return policy or that the total excludes shipping and handling.  127 char max.
+	'buyerid' => '', 			// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
+	'buyerusername' => '', 			// The user name of the user at the marketplaces site.
+	'buyerregistrationdate' => '',  	// Date when the user registered with the marketplace.
+	'allowpushfunding' => '', 		// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
+	'userselectedfundingsource' => '', 	// This element could be used to specify the preferred funding option for a guest user.  However, the LANDINGPAGE element must also be set to Billing.  Otherwise, it is ignored.  Values:  BML, ChinaUnionPay, CreditCard, ELV, Finance, QIWI
+	'taxidtype' => '', 			// The buyer's tax ID type.  This field is required for Brazil and used for Brazil only.  Values:  BR_CPF for individuals and BR_CNPJ for businesses.
+	'taxid' => ''				// The buyer's tax ID.  This field is required for Brazil and used for Brazil only.  The tax ID is 11 single-byte characters for individutals and 14 single-byte characters for businesses.
+);
+
+// Basic array of survey choices.  Nothing but the values should go in here.  
+$SurveyChoices = array('Choice 1', 'Choice2', 'Choice3', 'etc');
+
+$Payments = array();
+$Payment = array(
+    'amt' => '', 			// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+    'currencycode' => '', 		// A three-character currency code.  Default is USD.
+    'itemamt' => '', 			// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
+    'shippingamt' => '', 		// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+    'shipdiscamt' => '', 		// Shipping discount for this order, specified as a negative number.
+    'insuranceamt' => '', 		// Total shipping insurance costs for this order.
+    'insuranceoptionoffered' => '', 	// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+    'handlingamt' => '', 		// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+    'taxamt' => '', 			// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
+    'desc' => '', 			// Description of items on the order.  127 char max.
+    'custom' => '', 			// Free-form field for your own use.  256 char max.
+    'invnum' => '', 			// Your own invoice or tracking number.  127 char max.
+    'notifyurl' => '', 			// URL for receiving Instant Payment Notifications
+    'multishipping' => '', 		// The value 1 indicates that this payment is associated with multiple shipping addresses.
+    'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+    'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+    'shiptostreet2' => '', 		// Second street address.  100 char max.
+    'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+    'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+    'shiptozip' => '', 			// Required if shipping is included.  Postal code of shipping address.  20 char max.
+    'shiptocountrycode' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+    'shiptophonenum' => '',  		// Phone number for shipping address.  20 char max.
+    'notetext' => '', 			// Note to the merchant.  255 char max.
+    'allowedpaymentmethod' => '', 	// The payment method type.  Specify the value InstantPaymentOnly.
+    'paymentaction' => '', 		// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order.
+    'paymentrequestid' => '',  		// A unique identifier of the specific payment request, which is required for parallel payments.
+    'sellerpaypalaccountid' => '',	// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+    'transactionid' => '',		// Transaction ID number of the transaction that was created.  You can specify up to 10 payments.
+    'bucketcategorytype' => '',         // The category of a payment.  Values are:  1 - International shipping, 2 - Local delivery, 3 - BOPIS (Buy online pick-up in store), 4 - PUDO (Pick up drop off)
+    'location_type' => '',              // The type of merchant location.  Set this field if the items purchased will not be shipped, such as, BOPIS transactions.  Values are: 1 - Consumer, 2 - Store, for BOPIS transactions, 3 - PUDO
+    'location_id' => '',                // The Location ID specified by the merchant for BOPIS or PUDO transactions.
+);
+				
+$PaymentOrderItems = array();
+$Item = array(
+	'name' => '', 				// Item name. 127 char max.
+	'desc' => '', 				// Item description. 127 char max.
+	'amt' => '', 				// Cost of item.
+	'number' => '', 			// Item number.  127 char max.
+	'qty' => '', 				// Item qty on order.  Any positive integer.
+	'taxamt' => '', 			// Item sales tax
+	'itemurl' => '', 			// URL for the item.
+	'itemcategory' => '', 			// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 		// The weight value of the item.
+	'itemweightunit' => '', 		// The weight unit of the item.
+	'itemheightvalue' => '', 		// The height value of the item.
+	'itemheightunit' => '', 		// The height unit of the item.
+	'itemwidthvalue' => '', 		// The width value of the item.
+	'itemwidthunit' => '', 			// The width unit of the item.
+	'itemlengthvalue' => '', 		// The length value of the item.
+	'itemlengthunit' => '',  		// The length unit of the item.
+	'ebayitemnumber' => '', 		// Auction item number.  
+	'ebayitemauctiontxnid' => '', 		// Auction transaction ID number.  
+	'ebayitemorderid' => '',  		// Auction order ID number.
+	'ebayitemcartid' => ''			// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+$Payment['order_items'] = $PaymentOrderItems;
+
+array_push($Payments, $Payment);
+
+$BuyerDetails = array(
+	'buyerid' => '', 			// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
+	'buyerusername' => '', 			// The username of the marketplace site.
+	'buyerregistrationdate' => ''		// The registration of the buyer with the marketplace.
+);
+						
+// For shipping options we create an array of all shipping choices similar to how order items works.
+$ShippingOptions = array();
+$Option = array(
+	'l_shippingoptionisdefault' => '', 	// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
+	'l_shippingoptionname' => '', 		// Shipping option name.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionlabel' => '', 		// Shipping option label.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionamount' => '' 		// Shipping option amount.  Required if specifying the Callback URL.  
+);
+array_push($ShippingOptions, $Option);
+		
+$BillingAgreements = array();
+$Item = array(
+	'l_billingtype' => '', 				// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
+	'l_billingagreementdescription' => '', 		// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
+	'l_paymenttype' => '', 				// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
+	'l_billingagreementcustom' => ''		// Custom annotation field for your own use.  256 char max.
+);
+
+array_push($BillingAgreements, $Item);
+
+$PayPalRequestData = array(
+	'SECFields' => $SECFields, 
+	'SurveyChoices' => $SurveyChoices, 
+	'Payments' => $Payments, 
+	'BuyerDetails' => $BuyerDetails, 
+	'ShippingOptions' => $ShippingOptions, 
+	'BillingAgreements' => $BillingAgreements
+);
+
+$PaymentResult = $PayPal->CreatePayment($PayPalRequestData);
+
+// Save approval URL to session
+$_SESSION['PayPalPaymentID'] = $PaymentResult['RESPONSE']['id'];
+
+// Redirect user to PayPal approval URL
+$ApprovalUrl = '';
+foreach ($PaymentResult['RESPONSE']['links'] as $link) {
+    if ($link['rel'] === 'approval_url') {
+        $ApprovalUrl = $link['href'];
+        break;
+    }
+}
+
+echo 'Click here to continue.

'; +echo '
';
+print_r($PaymentResult);
\ No newline at end of file

From b7bc3436a7b53a2a860ae82c3b72aed0b5098c0d Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 27 Oct 2025 17:43:23 +0530
Subject: [PATCH 017/146] DoDirect and ExcutePayment Method Conversion

---
 samples/classic/DoDirectPayment.php         | 176 ++++++++++----------
 samples/classic/ExecutePayment.php          |  38 +++--
 samples/rest/DoDirectPayment.php            | 124 ++++++++++++++
 samples/rest/DoExpressCheckoutPayment.php   |   4 +-
 samples/rest/ExecutePayment.php             |  34 ++++
 src/angelleye/PayPal/PayPalREST.php         |  67 +++++++-
 templates/classic/DoDirectPayment.php       | 163 +++++++++---------
 templates/classic/ExecutePayment.php        |  38 +++--
 templates/rest/DoDirectPayment.php          | 127 ++++++++++++++
 templates/rest/DoExpressCheckoutPayment.php |   6 +-
 templates/rest/ExecutePayment.php           |  34 ++++
 11 files changed, 598 insertions(+), 213 deletions(-)
 create mode 100644 samples/rest/DoDirectPayment.php
 create mode 100644 samples/rest/ExecutePayment.php
 create mode 100644 templates/rest/DoDirectPayment.php
 create mode 100644 templates/rest/ExecutePayment.php

diff --git a/samples/classic/DoDirectPayment.php b/samples/classic/DoDirectPayment.php
index 7756ab5a..3b4bc1d5 100644
--- a/samples/classic/DoDirectPayment.php
+++ b/samples/classic/DoDirectPayment.php
@@ -3,117 +3,119 @@
 require_once('../../autoload.php');
 
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,					
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $DPFields = array(
-					'paymentaction' => 'Sale', 						// How you want to obtain payment.  Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.  Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
-					'ipaddress' => $_SERVER['REMOTE_ADDR'], 							// Required.  IP address of the payer's browser.
-					'returnfmfdetails' => '1' 					// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
-				);
+	'paymentaction' => 'Sale', 				// How you want to obtain payment.  Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.  Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
+	'ipaddress' => $_SERVER['REMOTE_ADDR'], 		// Required.  IP address of the payer's browser.
+	'returnfmfdetails' => '1' 				// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
+);
 				
 $CCDetails = array(
-					'creditcardtype' => 'Visa', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-					'acct' => '4716392328094345', 								// Required.  Credit card number.  No spaces or punctuation.
-					'expdate' => '022020', 							// Required.  Credit card expiration date.  Format is MMYYYY
-					'cvv2' => '456', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-					'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-					'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-				);
+	'creditcardtype' => 'Visa', 		// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '4716392328094345', 		// Required.  Credit card number.  No spaces or punctuation.
+	'expdate' => '022026', 			// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '456', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 			// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''			// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 				
 $PayerInfo = array(
-					'email' => 'sandbox@angelleye.com', 								// Email address of payer.
-					'payerid' => '', 							// Unique PayPal customer ID for payer.
-					'payerstatus' => '', 						// Status of payer.  Values are verified or unverified
-					'business' => '' 							// Payer's business name.
-				);
+	'email' => 'sb-j47z3s6571663@business.example.com', 	// Email address of payer.
+	'payerid' => '', 					// Unique PayPal customer ID for payer.
+	'payerstatus' => '', 					// Status of payer.  Values are verified or unverified
+	'business' => '' 					// Payer's business name.
+);
 				
 $PayerName = array(
-					'salutation' => '', 						// Payer's salutation.  20 char max.
-					'firstname' => 'Tester', 							// Payer's first name.  25 char max.
-					'middlename' => '', 						// Payer's middle name.  25 char max.
-					'lastname' => 'Testerson', 							// Payer's last name.  25 char max.
-					'suffix' => ''								// Payer's suffix.  12 char max.
-				);
+	'salutation' => '', 			// Payer's salutation.  20 char max.
+	'firstname' => 'Tester', 		// Payer's first name.  25 char max.
+	'middlename' => '', 			// Payer's middle name.  25 char max.
+	'lastname' => 'Testerson', 		// Payer's last name.  25 char max.
+	'suffix' => ''				// Payer's suffix.  12 char max.
+);
 				
 $BillingAddress = array(
-						'street' => '707 W. Bay Drive', 						// Required.  First street address.
-						'street2' => '', 						// Second street address.
-						'city' => 'Largo', 							// Required.  Name of City.
-						'state' => 'FL', 							// Required. Name of State or Province.
-						'countrycode' => 'US', 					// Required.  Country code.
-						'zip' => '33770', 							// Required.  Postal code of payer.
-						'phonenum' => '' 						// Phone Number of payer.  20 char max.
-					);
+	'street' => '707 W. Bay Drive', 	// Required.  First street address.
+	'street2' => '', 			// Second street address.
+	'city' => 'Largo', 			// Required.  Name of City.
+	'state' => 'FL', 			// Required. Name of State or Province.
+	'countrycode' => 'US', 			// Required.  Country code.
+	'zip' => '33770', 			// Required.  Postal code of payer.
+	'phonenum' => '' 			// Phone Number of payer.  20 char max.
+);
 					
 $ShippingAddress = array(
-						'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-						'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-						'shiptostreet2' => '', 					// Second street address.  100 char max.
-						'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-						'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-						'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-						'shiptocountrycode' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
-						'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-						);
+	'shiptoname' => '', 			// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 			// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 			// Second street address.  100 char max.
+	'shiptocity' => '', 			// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 			// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 			// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountrycode' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''			// Phone number for shipping address.  20 char max.
+);
 					
 $PaymentDetails = array(
-						'amt' => '3.00', 							// Required.  Total amount of order, including shipping, handling, and tax.  
-						'currencycode' => 'USD', 					// Required.  Three-letter currency code.  Default is USD.
-						'itemamt' => '', 						// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
-						'shippingamt' => '', 					// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
-						'handlingamt' => '', 					// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
-						'taxamt' => '', 						// Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax. 
-						'desc' => 'Testing Payments Pro DESC Field', 							// Description of the order the customer is purchasing.  127 char max.
-						'custom' => 'TEST', 						// Free-form field for your own use.  256 char max.
-						'invnum' => 'ZZZ-123-ABC', 						// Your own invoice or tracking number
-						'buttonsource' => '', 					// An ID code for use by 3rd party apps to identify transactions.
-						'notifyurl' => ''						// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
-					);
+	'amt' => '3.00', 					// Required.  Total amount of order, including shipping, handling, and tax.  
+	'currencycode' => 'USD', 				// Required.  Three-letter currency code.  Default is USD.
+	'itemamt' => '', 					// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
+	'shippingamt' => '', 					// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
+	'handlingamt' => '', 					// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
+	'taxamt' => '', 					// Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax. 
+	'desc' => 'Testing Payments Pro DESC Field', 		// Description of the order the customer is purchasing.  127 char max.
+	'custom' => 'TEST', 					// Free-form field for your own use.  256 char max.
+	'invnum' => 'ZZZ-123-ABC', 				// Your own invoice or tracking number
+	'buttonsource' => '', 					// An ID code for use by 3rd party apps to identify transactions.
+	'notifyurl' => ''					// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
+);
 
 $OrderItems = array();		
 $Item	 = array(
-						'l_name' => 'Test Widget', 						// Item Name.  127 char max.
-						'l_desc' => 'This is a test widget description.', 						// Item description.  127 char max.
-						'l_amt' => '1.00', 							// Cost of individual item.
-						'l_number' => 'ABC-123', 						// Item Number.  127 char max.
-						'l_qty' => '1', 							// Item quantity.  Must be any positive integer.  
-						'l_taxamt' => '', 						// Item's sales tax amount.
-						'l_ebayitemnumber' => '', 				// eBay auction number of item.
-						'l_ebayitemauctiontxnid' => '', 		// eBay transaction ID of purchased item.
-						'l_ebayitemorderid' => '' 				// eBay order ID for the item.
-				);
+	'l_name' => 'Test Widget', 				// Item Name.  127 char max.
+	'l_desc' => 'This is a test widget description.', 	// Item description.  127 char max.
+	'l_amt' => '1.00', 					// Cost of individual item.
+	'l_number' => 'ABC-123', 				// Item Number.  127 char max.
+	'l_qty' => '1', 					// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '', 					// Item's sales tax amount.
+	'l_ebayitemnumber' => '', 				// eBay auction number of item.
+	'l_ebayitemauctiontxnid' => '', 			// eBay transaction ID of purchased item.
+	'l_ebayitemorderid' => '' 				// eBay order ID for the item.
+);
 array_push($OrderItems, $Item);
 
 $Item	 = array(
-						'l_name' => 'Test Widget 2', 						// Item Name.  127 char max.
-						'l_desc' => 'This is a test widget description.', 						// Item description.  127 char max.
-						'l_amt' => '2.00', 							// Cost of individual item.
-						'l_number' => 'ABC-XYZ', 						// Item Number.  127 char max.
-						'l_qty' => '1', 							// Item quantity.  Must be any positive integer.  
-						'l_taxamt' => '', 						// Item's sales tax amount.
-						'l_ebayitemnumber' => '', 				// eBay auction number of item.
-						'l_ebayitemauctiontxnid' => '', 		// eBay transaction ID of purchased item.
-						'l_ebayitemorderid' => '' 				// eBay order ID for the item.
-				);
+	'l_name' => 'Test Widget 2', 				// Item Name.  127 char max.
+	'l_desc' => 'This is a test widget description.', 	// Item description.  127 char max.
+	'l_amt' => '2.00', 					// Cost of individual item.
+	'l_number' => 'ABC-XYZ', 				// Item Number.  127 char max.
+	'l_qty' => '1', 					// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '', 					// Item's sales tax amount.
+	'l_ebayitemnumber' => '', 				// eBay auction number of item.
+	'l_ebayitemauctiontxnid' => '', 			// eBay transaction ID of purchased item.
+	'l_ebayitemorderid' => '' 				// eBay order ID for the item.
+);
 array_push($OrderItems, $Item);
 
 $PayPalRequestData = array(
-						   'DPFields' => $DPFields, 
-						   'CCDetails' => $CCDetails, 
-						   'PayerInfo' => $PayerInfo,
-						   'PayerName' => $PayerName, 
-						   'BillingAddress' => $BillingAddress, 
-						   'PaymentDetails' => $PaymentDetails, 
-						   'OrderItems' => $OrderItems
-						   );
+	'DPFields' => $DPFields, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo,
+	'PayerName' => $PayerName, 
+	'BillingAddress' => $BillingAddress, 
+	'PaymentDetails' => $PaymentDetails, 
+	'OrderItems' => $OrderItems
+);
 
 $PayPalResult = $PayPal -> DoDirectPayment($PayPalRequestData);
 
diff --git a/samples/classic/ExecutePayment.php b/samples/classic/ExecutePayment.php
index 2e0d0a7d..e285b1f4 100644
--- a/samples/classic/ExecutePayment.php
+++ b/samples/classic/ExecutePayment.php
@@ -6,32 +6,34 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $ExecutePaymentFields = array(
-							'PayKey' => 'AP-7X219188NE705973T', 								// The pay key that identifies the payment to be executed.  This is the key returned in the PayResponse message.
-							'FundingPlanID' => '' 							// The ID of the funding plan from which to make this payment.
-							);
+	'PayKey' => 'AP-7X219188NE705973T', 	// The pay key that identifies the payment to be executed.  This is the key returned in the PayResponse message.
+	'FundingPlanID' => '' 			// The ID of the funding plan from which to make this payment.
+);
 							
 $PayPalRequestData = array('ExecutePaymentFields' => $ExecutePaymentFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->ExecutePayment($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->ExecutePayment($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/DoDirectPayment.php b/samples/rest/DoDirectPayment.php
new file mode 100644
index 00000000..a24451db
--- /dev/null
+++ b/samples/rest/DoDirectPayment.php
@@ -0,0 +1,124 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,					
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$DPFields = array(
+	'paymentaction' => 'CAPTURE', 				// How you want to obtain payment.  Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.  Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
+	'ipaddress' => $_SERVER['REMOTE_ADDR'], 		// Required.  IP address of the payer's browser.
+	'returnfmfdetails' => '1' 				// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
+);
+				
+$CCDetails = array(
+	'creditcardtype' => 'Visa', 		// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '4716392328094345', 		// Required.  Credit card number.  No spaces or punctuation.
+	'expdate' => '2026-01', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '456', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 			// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''			// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
+				
+$PayerInfo = array(
+	'email' => 'sandbox@angelleye.com', 	// Email address of payer.
+	'payerid' => '', 			// Unique PayPal customer ID for payer.
+	'payerstatus' => '', 			// Status of payer.  Values are verified or unverified
+	'business' => '' 			// Payer's business name.
+);
+				
+$PayerName = array(
+	'salutation' => '', 			// Payer's salutation.  20 char max.
+	'firstname' => 'John', 			// Payer's first name.  25 char max.
+	'middlename' => '', 			// Payer's middle name.  25 char max.
+	'lastname' => 'Doe',	 		// Payer's last name.  25 char max.
+	'suffix' => ''				// Payer's suffix.  12 char max.
+);
+				
+$BillingAddress = array(
+	'street' => '707 W. Bay Drive', 	// Required.  First street address.
+	'street2' => '', 			// Second street address.
+	'city' => 'Largo', 			// Required.  Name of City.
+	'state' => 'FL', 			// Required. Name of State or Province.
+	'countrycode' => 'US', 			// Required.  Country code.
+	'zip' => '33770', 			// Required.  Postal code of payer.
+	'phonenum' => '' 			// Phone Number of payer.  20 char max.
+);
+					
+$ShippingAddress = array(
+	'shiptoname' => '', 			// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 			// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 			// Second street address.  100 char max.
+	'shiptocity' => '', 			// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 			// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 			// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountrycode' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''			// Phone number for shipping address.  20 char max.
+);
+					
+$PaymentDetails = array(
+	'amt' => '3.00', 					// Required.  Total amount of order, including shipping, handling, and tax.  
+	'currencycode' => 'USD', 				// Required.  Three-letter currency code.  Default is USD.
+	'itemamt' => '', 					// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
+	'shippingamt' => '', 					// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
+	'handlingamt' => '', 					// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
+	'taxamt' => '', 					// Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax. 
+	'desc' => 'Testing Payments Pro DESC Field', 		// Description of the order the customer is purchasing.  127 char max.
+	'custom' => 'TEST', 					// Free-form field for your own use.  256 char max.
+	'invnum' => 'ZZZ-123-ABC', 				// Your own invoice or tracking number
+	'buttonsource' => '', 					// An ID code for use by 3rd party apps to identify transactions.
+	'notifyurl' => ''					// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
+);
+
+$OrderItems = array();		
+$Item	 = array(
+	'l_name' => 'Test Widget', 				// Item Name.  127 char max.
+	'l_desc' => 'This is a test widget description.', 	// Item description.  127 char max.
+	'l_amt' => '1.00', 					// Cost of individual item.
+	'l_number' => 'ABC-123', 				// Item Number.  127 char max.
+	'l_qty' => '1', 					// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '', 					// Item's sales tax amount.
+	'l_ebayitemnumber' => '', 				// eBay auction number of item.
+	'l_ebayitemauctiontxnid' => '', 			// eBay transaction ID of purchased item.
+	'l_ebayitemorderid' => '' 				// eBay order ID for the item.
+);
+array_push($OrderItems, $Item);
+
+$Item	 = array(
+	'l_name' => 'Test Widget 2', 				// Item Name.  127 char max.
+	'l_desc' => 'This is a test widget description.', 	// Item description.  127 char max.
+	'l_amt' => '2.00', 					// Cost of individual item.
+	'l_number' => 'ABC-XYZ', 				// Item Number.  127 char max.
+	'l_qty' => '1', 					// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '', 					// Item's sales tax amount.
+	'l_ebayitemnumber' => '', 				// eBay auction number of item.
+	'l_ebayitemauctiontxnid' => '', 			// eBay transaction ID of purchased item.
+	'l_ebayitemorderid' => '' 				// eBay order ID for the item.
+);
+array_push($OrderItems, $Item);
+
+$PayPalRequestData = array(
+	'DPFields' => $DPFields, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo,
+	'PayerName' => $PayerName, 
+	'BillingAddress' => $BillingAddress, 
+	'PaymentDetails' => $PaymentDetails, 
+	'OrderItems' => $OrderItems
+);
+
+$PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
+
+$_SESSION['transaction_id'] = isset($PayPalResult['RESPONSE']['id']) ? $PayPalResult['RESPONSE']['id'] : '';
+
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/DoExpressCheckoutPayment.php b/samples/rest/DoExpressCheckoutPayment.php
index 5ee5117c..ed69d3c2 100644
--- a/samples/rest/DoExpressCheckoutPayment.php
+++ b/samples/rest/DoExpressCheckoutPayment.php
@@ -16,8 +16,8 @@
 
 $PayPalRequestedData = array(
 	'paymentID' => isset($_GET['paymentId']) ? $_GET['paymentId'] : '',
-	'token' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
-	'payerID' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
+	'token' => isset($_GET['token']) ? $_GET['token'] : '',
+	'PayerID' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
 );
 
 $ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
diff --git a/samples/rest/ExecutePayment.php b/samples/rest/ExecutePayment.php
new file mode 100644
index 00000000..532d1173
--- /dev/null
+++ b/samples/rest/ExecutePayment.php
@@ -0,0 +1,34 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$PayPalRequestedData = array(
+	'paymentID' => 'PAYID-ND7VMCY2TJ817399J8265422',	// Test Payment ID
+	'token' => 'EC-4BC82606XT4947400',			// Test Token
+	'PayerID' => 'QSXYL9LZ8NEYC',				// Test Payer ID
+);
+
+$ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
+
+echo '
';
+print_r($ExecuteResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index c2061ad5..c7c09627 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -47,7 +47,7 @@ public function test()
     /**
      * Get standard headers for API requests
      */
-    private function getHeaders($includeAuth = true, $contentType = 'application/json')
+    private function getHeaders($includeAuth = true, $contentType = 'application/json', $requestId = null)
     {
         $headers = [
         'Content-Type: ' . $contentType,
@@ -60,6 +60,10 @@ private function getHeaders($includeAuth = true, $contentType = 'application/jso
             $headers[] = 'Authorization: Bearer ' . $token;
         }
 
+        if (!empty($requestId)) {
+            $headers[] = 'PayPal-Request-Id: ' . $requestId;
+        }
+
         return $headers;
     }
 
@@ -119,9 +123,9 @@ private function getAccessToken()
     /**
      * Make authenticated REST API request
      */
-    protected function makeRequest($endpoint, $method = 'GET', $data = null)
+    protected function makeRequest($endpoint, $method = 'GET', $data = null, $requestId = null)
     {
-        $headers = $this->getHeaders(true);
+        $headers = $this->getHeaders(true, 'application/json', $requestId);
 
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $this->base_url . $endpoint);
@@ -577,7 +581,7 @@ public function CreatePayment($paymentData) {
 
     public function ExecutePayment($paymentData) {
         $data = [
-            'payer_id' => !empty($paymentData['payerID']) ? $paymentData['payerID'] : ''
+            'payer_id' => !empty($paymentData['PayerID']) ? $paymentData['PayerID'] : ''
         ];
 
         $paymentID = !empty($paymentData['paymentID']) ? $paymentData['paymentID'] : '';
@@ -606,6 +610,61 @@ public function ExecutePayment($paymentData) {
         return $responseSimplified;
     }
 
+    public function DoDirectPayment($paymentData) {
+        $paymentsMappedData = [];
+
+        $paymentsMappedData['intent'] = !empty($paymentData['DPFields']['paymentaction']) ? $paymentData['DPFields']['paymentaction'] : 'sale';
+        $paymentsMappedData['purchase_units'] = [
+            [
+                'amount' => [
+                    'currency_code' => !empty($paymentData['PaymentDetails']['currencycode']) ? $paymentData['PaymentDetails']['currencycode'] : '',
+                    'value' => !empty($paymentData['PaymentDetails']['amt']) ? $paymentData['PaymentDetails']['amt'] : 0.00,
+                ]
+            ]
+        ];
+
+        $paymentsMappedData['payment_source'] = [
+            'card' => [
+                'number' => !empty($paymentData['CCDetails']['acct']) ? $paymentData['CCDetails']['acct'] : '',
+                'expiry' => !empty($paymentData['CCDetails']['expdate']) ? $paymentData['CCDetails']['expdate'] : '',
+                'security_code' => !empty($paymentData['CCDetails']['cvv2']) ? $paymentData['CCDetails']['cvv2'] : '',
+                'name' => (!empty($paymentData['PayerName']['firstname']) ? $paymentData['PayerName']['firstname'] : '') . ' ' . (!empty($paymentData['PayerName']['lastname']) ? $paymentData['PayerName']['lastname'] : ''),
+                'billing_address' => [
+                    'address_line_1' => !empty($paymentData['BillingAddress']['street']) ? $paymentData['BillingAddress']['street'] : '',
+                    'admin_area_2' => !empty($paymentData['BillingAddress']['city']) ? $paymentData['BillingAddress']['city'] : '',
+                    'admin_area_1' => !empty($paymentData['BillingAddress']['state']) ? $paymentData['BillingAddress']['state'] : '',
+                    'postal_code' => !empty($paymentData['BillingAddress']['zip']) ? $paymentData['BillingAddress']['zip'] : '',
+                    'country_code' => !empty($paymentData['BillingAddress']['countrycode']) ? $paymentData['BillingAddress']['countrycode'] : ''
+                ]
+            ]  
+        ];
+
+        $paypalRequestId = uniqid('pprid_', true);
+
+        $response = $this->makeRequest('/v2/checkout/orders', 'POST', $paymentsMappedData, $paypalRequestId);
+
+        $responseSimplified = [];
+
+        // Handle Response
+        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
+            $responseSimplified = array(
+                'SUCCESS' => true,
+                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        } else {
+            $responseSimplified = array(
+                'SUCCESS' => false,
+                'STATUSCODE' => $response['status_code'],
+                'ERRORS' => !empty($response['body']) ? $response['body'] : ['invalid_payment' => 'Payment execution failed'],
+                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/DoDirectPayment.php b/templates/classic/DoDirectPayment.php
index 2f700bf4..fd607673 100644
--- a/templates/classic/DoDirectPayment.php
+++ b/templates/classic/DoDirectPayment.php
@@ -5,77 +5,78 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $DPFields = array(
-    'paymentaction' => '', 						// How you want to obtain payment.  Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.  Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
-    'ipaddress' => '', 							// Required.  IP address of the payer's browser.
-    'returnfmfdetails' => '', 					// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
-    'softdescriptor' => '',                     // Information that is usually displayed in the account holder's statement.  23 char max.
-    'softdescriptorcity' => '',                 // A unique phone number, emaili address or URL, which is displayed on the account holder's statement.
+    'paymentaction' => '', 		// How you want to obtain payment.  Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.  Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
+    'ipaddress' => '', 			// Required.  IP address of the payer's browser.
+    'returnfmfdetails' => '', 		// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
+    'softdescriptor' => '',    		// Information that is usually displayed in the account holder's statement.  23 char max.
+    'softdescriptorcity' => '',         // A unique phone number, emaili address or URL, which is displayed on the account holder's statement.
 );
 				
 $CCDetails = array(
-					'creditcardtype' => '', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-					'acct' => '', 								// Required.  Credit card number.  No spaces or punctuation.  
-					'expdate' => '', 							// Required.  Credit card expiration date.  Format is MMYYYY
-					'cvv2' => '', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-					'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-					'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-				);
+	'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 				
 $PayerInfo = array(
-					'email' => '', 								// Email address of payer.
-					'firstname' => '', 							// Required.  Payer's first name.
-					'lastname' => '' 							// Required.  Payer's last name.
-				);
+	'email' => '', 			// Email address of payer.
+	'firstname' => '', 		// Required.  Payer's first name.
+	'lastname' => '' 		// Required.  Payer's last name.
+);
 				
 $BillingAddress = array(
-						'street' => '', 						// Required.  First street address.
-						'street2' => '', 						// Second street address.
-						'city' => '', 							// Required.  Name of City.
-						'state' => '', 							// Required. Name of State or Province.
-						'countrycode' => '', 					// Required.  Country code.
-						'zip' => '', 							// Required.  Postal code of payer.
-						'phonenum' => '' 						// Phone Number of payer.  20 char max.
-					);
+	'street' => '', 		// Required.  First street address.
+	'street2' => '', 		// Second street address.
+	'city' => '', 			// Required.  Name of City.
+	'state' => '', 			// Required. Name of State or Province.
+	'countrycode' => '', 		// Required.  Country code.
+	'zip' => '', 			// Required.  Postal code of payer.
+	'phonenum' => '' 		// Phone Number of payer.  20 char max.
+);
 					
 $ShippingAddress = array(
-						'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-						'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-						'shiptostreet2' => '', 					// Second street address.  100 char max.
-						'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-						'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-						'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-						'shiptocountry' => '', 					// Required if shipping is included.  Country code of shipping address.  2 char max.
-						'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-						);
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
 					
 $PaymentDetails = array(
-						'amt' => '', 							// Required.  Total amount of order, including shipping, handling, and tax.  
-						'currencycode' => '', 					// Required.  Three-letter currency code.  Default is USD.
-						'itemamt' => '', 						// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
-						'shippingamt' => '', 					// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
-						'insuranceamt' => '', 					// Total shipping insurance costs for this order.  
-						'shipdiscamt' => '', 					// Shipping discount for the order, specified as a negative number.
-						'handlingamt' => '', 					// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
-						'taxamt' => '', 						// Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax. 
-						'desc' => '', 							// Description of the order the customer is purchasing.  127 char max.
-						'custom' => '', 						// Free-form field for your own use.  256 char max.
-						'invnum' => '', 						// Your own invoice or tracking number
-						'notifyurl' => '', 						// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
-						'recurring' => ''						// Flag to indicate a recurring transaction.  Value should be Y for recurring, or anything other than Y if it's not recurring.  To pass Y here, you must have an established billing agreement with the buyer.
-					);
+	'amt' => '', 			// Required.  Total amount of order, including shipping, handling, and tax.  
+	'currencycode' => '', 		// Required.  Three-letter currency code.  Default is USD.
+	'itemamt' => '', 		// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
+	'shippingamt' => '', 		// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
+	'insuranceamt' => '', 		// Total shipping insurance costs for this order.  
+	'shipdiscamt' => '', 		// Shipping discount for the order, specified as a negative number.
+	'handlingamt' => '', 		// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
+	'taxamt' => '', 		// Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax. 
+	'desc' => '', 			// Description of the order the customer is purchasing.  127 char max.
+	'custom' => '', 		// Free-form field for your own use.  256 char max.
+	'invnum' => '', 		// Your own invoice or tracking number
+	'notifyurl' => '', 		// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
+	'recurring' => ''		// Flag to indicate a recurring transaction.  Value should be Y for recurring, or anything other than Y if it's not recurring.  To pass Y here, you must have an established billing agreement with the buyer.
+);
 
 // For order items you populate a nested array with multiple $Item arrays.  Normally you'll be looping through cart items to populate the $Item 
 // array and then push it into the $OrderItems array at the end of each loop for an entire collection of all items in $OrderItems.
@@ -83,16 +84,16 @@
 $OrderItems = array();		
 	
 $Item	 = array(
-						'l_name' => '', 						// Item Name.  127 char max.
-						'l_desc' => '', 						// Item description.  127 char max.
-						'l_amt' => '', 							// Cost of individual item.
-						'l_number' => '', 						// Item Number.  127 char max.
-						'l_qty' => '', 							// Item quantity.  Must be any positive integer.  
-						'l_taxamt' => '', 						// Item's sales tax amount.
-						'l_ebayitemnumber' => '', 				// eBay auction number of item.
-						'l_ebayitemauctiontxnid' => '', 		// eBay transaction ID of purchased item.
-						'l_ebayitemorderid' => '' 				// eBay order ID for the item.
-				);
+	'l_name' => '', 			// Item Name.  127 char max.
+	'l_desc' => '', 			// Item description.  127 char max.
+	'l_amt' => '', 				// Cost of individual item.
+	'l_number' => '', 			// Item Number.  127 char max.
+	'l_qty' => '', 				// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '', 			// Item's sales tax amount.
+	'l_ebayitemnumber' => '', 		// eBay auction number of item.
+	'l_ebayitemauctiontxnid' => '', 	// eBay transaction ID of purchased item.
+	'l_ebayitemorderid' => '' 		// eBay order ID for the item.
+);
 
 array_push($OrderItems, $Item);
 
@@ -100,23 +101,23 @@
  * Important note : 3-D Secure Request Fields (UK Merchants Only)
  */
 $Secure3D = array(
-				  'authstatus3ds' => '', 					     // (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the PAResStatus value returned by cmpi_authenticate. Otherwise, set this field to blank.
-				  'mpivendor3ds' => '', 						 // (Optional) A value returned by CardinalCommerce. Set this field to the Enrolled value returned by cmpi_lookup.
-				  'cavv' => '', 								 // (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the Cavv value returned by cmpi_authenticate. Otherwise, set this field to blank.	
-				  'eci3ds' => '',								 // (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the EciFlag value returned by cmpi_authenticate. Otherwise, set this field to the EciFlag value returned by cmpi_lookup.
-				  'xid' => ''									 // (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the Xid value returned by cmpi_authenticate. Otherwise, set this field to blank.	
-				  );
+	'authstatus3ds' => '', 		// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the PAResStatus value returned by cmpi_authenticate. Otherwise, set this field to blank.
+	'mpivendor3ds' => '', 		// (Optional) A value returned by CardinalCommerce. Set this field to the Enrolled value returned by cmpi_lookup.
+	'cavv' => '', 			// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the Cavv value returned by cmpi_authenticate. Otherwise, set this field to blank.	
+	'eci3ds' => '',			// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the EciFlag value returned by cmpi_authenticate. Otherwise, set this field to the EciFlag value returned by cmpi_lookup.
+	'xid' => ''			// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the Xid value returned by cmpi_authenticate. Otherwise, set this field to blank.	
+);
 				  
 $PayPalRequestData = array(
-						   'DPFields' => $DPFields, 
-						   'CCDetails' => $CCDetails, 
-						   'PayerInfo' => $PayerInfo, 
-						   'BillingAddress' => $BillingAddress, 
-						   'ShippingAddress' => $ShippingAddress, 
-						   'PaymentDetails' => $PaymentDetails, 
-						   'OrderItems' => $OrderItems,
-						   'Secure3D' => $Secure3D,
-						   );
+	'DPFields' => $DPFields, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo, 
+	'BillingAddress' => $BillingAddress, 
+	'ShippingAddress' => $ShippingAddress, 
+	'PaymentDetails' => $PaymentDetails, 
+	'OrderItems' => $OrderItems,
+	'Secure3D' => $Secure3D,
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
diff --git a/templates/classic/ExecutePayment.php b/templates/classic/ExecutePayment.php
index 7ba56035..f78c3999 100644
--- a/templates/classic/ExecutePayment.php
+++ b/templates/classic/ExecutePayment.php
@@ -6,32 +6,34 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $ExecutePaymentFields = array(
-							'PayKey' => '', 								// The pay key that identifies the payment to be executed.  This is the key returned in the PayResponse message.
-							'FundingPlanID' => '' 							// The ID of the funding plan from which to make this payment.
-							);
+	'PayKey' => '', 		// The pay key that identifies the payment to be executed.  This is the key returned in the PayResponse message.
+	'FundingPlanID' => '' 		// The ID of the funding plan from which to make this payment.
+);
 							
 $PayPalRequestData = array('ExecutePaymentFields' => $ExecutePaymentFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->ExecutePayment($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->ExecutePayment($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/DoDirectPayment.php b/templates/rest/DoDirectPayment.php
new file mode 100644
index 00000000..e22cad84
--- /dev/null
+++ b/templates/rest/DoDirectPayment.php
@@ -0,0 +1,127 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$DPFields = array(
+    'paymentaction' => '', 		// How you want to obtain payment.  Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture.  Sale indicates that this is a final sale for which you are requesting payment.  Default is Sale.
+    'ipaddress' => '', 			// Required.  IP address of the payer's browser.
+    'returnfmfdetails' => '', 		// Flag to determine whether you want the results returned by FMF.  1 or 0.  Default is 0.
+    'softdescriptor' => '',    		// Information that is usually displayed in the account holder's statement.  23 char max.
+    'softdescriptorcity' => '',         // A unique phone number, emaili address or URL, which is displayed on the account holder's statement.
+);
+				
+$CCDetails = array(
+	'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
+				
+$PayerInfo = array(
+	'email' => '', 			// Email address of payer.
+	'firstname' => '', 		// Required.  Payer's first name.
+	'lastname' => '' 		// Required.  Payer's last name.
+);
+				
+$BillingAddress = array(
+	'street' => '', 		// Required.  First street address.
+	'street2' => '', 		// Second street address.
+	'city' => '', 			// Required.  Name of City.
+	'state' => '', 			// Required. Name of State or Province.
+	'countrycode' => '', 		// Required.  Country code.
+	'zip' => '', 			// Required.  Postal code of payer.
+	'phonenum' => '' 		// Phone Number of payer.  20 char max.
+);
+					
+$ShippingAddress = array(
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
+					
+$PaymentDetails = array(
+	'amt' => '', 			// Required.  Total amount of order, including shipping, handling, and tax.  
+	'currencycode' => '', 		// Required.  Three-letter currency code.  Default is USD.
+	'itemamt' => '', 		// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
+	'shippingamt' => '', 		// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
+	'insuranceamt' => '', 		// Total shipping insurance costs for this order.  
+	'shipdiscamt' => '', 		// Shipping discount for the order, specified as a negative number.
+	'handlingamt' => '', 		// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
+	'taxamt' => '', 		// Required if you specify itemized cart tax details. Sum of tax for all items on the order.  Total sales tax. 
+	'desc' => '', 			// Description of the order the customer is purchasing.  127 char max.
+	'custom' => '', 		// Free-form field for your own use.  256 char max.
+	'invnum' => '', 		// Your own invoice or tracking number
+	'notifyurl' => '', 		// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
+	'recurring' => ''		// Flag to indicate a recurring transaction.  Value should be Y for recurring, or anything other than Y if it's not recurring.  To pass Y here, you must have an established billing agreement with the buyer.
+);
+
+// For order items you populate a nested array with multiple $Item arrays.  Normally you'll be looping through cart items to populate the $Item 
+// array and then push it into the $OrderItems array at the end of each loop for an entire collection of all items in $OrderItems.
+
+$OrderItems = array();		
+	
+$Item	 = array(
+	'l_name' => '', 			// Item Name.  127 char max.
+	'l_desc' => '', 			// Item description.  127 char max.
+	'l_amt' => '', 				// Cost of individual item.
+	'l_number' => '', 			// Item Number.  127 char max.
+	'l_qty' => '', 				// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '', 			// Item's sales tax amount.
+	'l_ebayitemnumber' => '', 		// eBay auction number of item.
+	'l_ebayitemauctiontxnid' => '', 	// eBay transaction ID of purchased item.
+	'l_ebayitemorderid' => '' 		// eBay order ID for the item.
+);
+
+array_push($OrderItems, $Item);
+
+/**
+ * Important note : 3-D Secure Request Fields (UK Merchants Only)
+ */
+$Secure3D = array(
+	'authstatus3ds' => '', 		// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the PAResStatus value returned by cmpi_authenticate. Otherwise, set this field to blank.
+	'mpivendor3ds' => '', 		// (Optional) A value returned by CardinalCommerce. Set this field to the Enrolled value returned by cmpi_lookup.
+	'cavv' => '', 			// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the Cavv value returned by cmpi_authenticate. Otherwise, set this field to blank.	
+	'eci3ds' => '',			// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the EciFlag value returned by cmpi_authenticate. Otherwise, set this field to the EciFlag value returned by cmpi_lookup.
+	'xid' => ''			// (Optional) A value returned by CardinalCommerce. If the cmpi_lookup request returns Y for Enrolled, set this field to the Xid value returned by cmpi_authenticate. Otherwise, set this field to blank.	
+);
+				  
+$PayPalRequestData = array(
+	'DPFields' => $DPFields, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo, 
+	'BillingAddress' => $BillingAddress, 
+	'ShippingAddress' => $ShippingAddress, 
+	'PaymentDetails' => $PaymentDetails, 
+	'OrderItems' => $OrderItems,
+	'Secure3D' => $Secure3D,
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
+
+$_SESSION['transaction_id'] = isset($PayPalResult['RESPONSE']['id']) ? $PayPalResult['RESPONSE']['id'] : '';
+
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/DoExpressCheckoutPayment.php b/templates/rest/DoExpressCheckoutPayment.php
index 8cef089b..2842e639 100644
--- a/templates/rest/DoExpressCheckoutPayment.php
+++ b/templates/rest/DoExpressCheckoutPayment.php
@@ -18,9 +18,9 @@
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $PayPalRequestedData = array(
-	'paymentID' => isset($_GET['paymentId']) ? $_GET['paymentId'] : '',
-	'token' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
-	'payerID' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '',
+	'paymentID' => '',
+	'token' => '',
+	'PayerID' => '',
 );
 
 $ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
diff --git a/templates/rest/ExecutePayment.php b/templates/rest/ExecutePayment.php
new file mode 100644
index 00000000..0a9183cb
--- /dev/null
+++ b/templates/rest/ExecutePayment.php
@@ -0,0 +1,34 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$PayPalRequestedData = array(
+	'paymentID' => '',		// Test Payment ID
+	'token' => '',			// Test Token
+	'PayerID' => '',		// Test Payer ID
+);
+
+$ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
+
+echo '
';
+print_r($ExecuteResult);
\ No newline at end of file

From dd2cd02940eabf3f190f367e19158f31372fae70 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Fri, 31 Oct 2025 10:12:25 +0530
Subject: [PATCH 018/146] ExpressCheckout Demo with REST V2 with Capture Intent

---
 .../DoExpressCheckoutPayment.php              |   9 +-
 .../GetExpressCheckoutDetails.php             |   3 +-
 .../SetExpressCheckout.php                    |  41 ++--
 demo/error.php                                |  21 +-
 demo/index.php                                |   4 +-
 .../DoExpressCheckoutPayment.php              |  39 ++++
 .../GetExpressCheckoutDetails.php             |  92 ++++++++
 .../SetExpressCheckout.php                    |  83 +++++++
 .../rest-checkout-line-items-v2/index.php     | 142 ++++++++++++
 .../order-complete.php                        | 138 +++++++++++
 .../rest-checkout-line-items-v2/review.php    | 135 +++++++++++
 samples/classic/SetExpressCheckout.php        |   4 +-
 samples/rest/DoExpressCheckoutPayment.php     |  10 +-
 samples/rest/SetExpressCheckout.php           | 213 ++++-------------
 src/angelleye/PayPal/PayPalREST.php           | 102 --------
 templates/rest/DoExpressCheckoutPayment.php   |  10 +-
 templates/rest/SetExpressCheckout.php         | 217 ++++--------------
 17 files changed, 773 insertions(+), 490 deletions(-)
 create mode 100644 demo/rest/rest-checkout-line-items-v2/DoExpressCheckoutPayment.php
 create mode 100644 demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php
 create mode 100644 demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php
 create mode 100644 demo/rest/rest-checkout-line-items-v2/index.php
 create mode 100644 demo/rest/rest-checkout-line-items-v2/order-complete.php
 create mode 100644 demo/rest/rest-checkout-line-items-v2/review.php

diff --git a/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php b/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php
index f58d3644..bc813cdf 100644
--- a/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php
+++ b/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php
@@ -11,6 +11,7 @@
  */
 $PayPalConfig = array(
     'Sandbox' => $sandbox,
+    'PayPalAPIMode' => $api_mode,
     'APIUsername' => $api_username,
     'APIPassword' => $api_password,
     'APISignature' => $api_signature,
@@ -18,7 +19,7 @@
     'LogResults' => $log_results,
     'LogPath' => $log_path,
 );
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 /**
  * Now we'll setup the request params for the final call in the Express Checkout flow.
@@ -71,9 +72,9 @@
  * Now we gather all of the arrays above into a single array.
  */
 $PayPalRequestData = array(
-					   'DECPFields' => $DECPFields, 
-					   'Payments' => $Payments, 
-					   );
+    'DECPFields' => $DECPFields, 
+    'Payments' => $Payments, 
+);
 
 /**
  * Here we are making the call to the DoExpressCheckoutPayment function in the library,
diff --git a/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php b/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php
index bf0d4815..9d47371f 100644
--- a/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php
+++ b/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php
@@ -11,6 +11,7 @@
  */
 $PayPalConfig = array(
     'Sandbox' => $sandbox,
+    'PayPalAPIMode' => $api_mode,
     'APIUsername' => $api_username,
     'APIPassword' => $api_password,
     'APISignature' => $api_signature,
@@ -18,7 +19,7 @@
     'LogResults' => $log_results,
     'LogPath' => $log_path,
 );
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 /**
  * Now we pass the PayPal token that we saved to a session variable
diff --git a/demo/classic/express-checkout-basic/SetExpressCheckout.php b/demo/classic/express-checkout-basic/SetExpressCheckout.php
index 6f573653..222d21bc 100644
--- a/demo/classic/express-checkout-basic/SetExpressCheckout.php
+++ b/demo/classic/express-checkout-basic/SetExpressCheckout.php
@@ -10,15 +10,16 @@
  * Then load the PayPal object into $PayPal
  */
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 /**
  * Here we are setting up the parameters for a basic Express Checkout flow.
@@ -29,14 +30,14 @@
  * $domain used here is set in the config file.
  */
 $SECFields = array(
-					'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), 					// The expected maximum total amount the order will be, including S&H and sales tax.
-					'returnurl' => $domain . 'demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php', 							    // Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
-					'cancelurl' => $domain . 'demo/classic/express-checkout-basic/', 							    // Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
-					'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', 			// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
-					'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', 					// A URL to your logo image.  Formats:  .gif, .jpg, .png.  190x60.  PayPal places your logo image at the top of the cart review area.  This logo needs to be stored on a https:// server.
-					'brandname' => 'Angell EYE', 							                                // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
-					'customerservicenumber' => '816-555-5555', 				                                // Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
-				);
+	'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), 				// The expected maximum total amount the order will be, including S&H and sales tax.
+	'returnurl' => $domain . 'demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php', 		// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
+	'cancelurl' => $domain . 'demo/classic/express-checkout-basic/', 					// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
+	'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', 			// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
+	'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', 				// A URL to your logo image.  Formats:  .gif, .jpg, .png.  190x60.  PayPal places your logo image at the top of the cart review area.  This logo needs to be stored on a https:// server.
+	'brandname' => 'Angell EYE', 							                        // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
+	'customerservicenumber' => '816-555-5555', 				                                // Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
+);
 
 /**
  * Now we begin setting up our payment(s).
@@ -65,9 +66,9 @@
  * Now we gather all of the arrays above into a single array.
  */
 $PayPalRequestData = array(
-					   'SECFields' => $SECFields, 
-					   'Payments' => $Payments,
-					   );
+	'SECFields' => $SECFields, 
+	'Payments' => $Payments,
+);
 
 /**
  * Here we are making the call to the SetExpressCheckout function in the library,
diff --git a/demo/error.php b/demo/error.php
index cf306eea..f6e712d5 100755
--- a/demo/error.php
+++ b/demo/error.php
@@ -3,15 +3,18 @@
 require_once('../autoload.php');
 
 $PayPalConfig = array(
-    'Sandbox' => $sandbox,
-    'APIUsername' => $api_username,
-    'APIPassword' => $api_password,
-    'APISignature' => $api_signature,
-    'PrintHeaders' => $print_headers,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
+  'Sandbox' => $sandbox,
+  'PayPalAPIMode' => $api_mode,
+  'APIUsername' => $api_username,
+  'APIPassword' => $api_password,
+  'APISignature' => $api_signature,
+  'ClientID' => $rest_client_id,
+  'ClientSecret' => $rest_client_secret,
+  'PrintHeaders' => $print_headers,
+  'LogResults' => $log_results,
+  'LogPath' => $log_path,
 );
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 ?>
 
 
@@ -69,7 +72,7 @@
           unset($_SESSION['rest_errors']);
       }
       else{
-          $PayPal->DisplayErrors($_SESSION['paypal_errors']);
+        $PayPal->DisplayErrors($_SESSION['paypal_errors']);
       }
 	  ?>
       
diff --git a/demo/index.php b/demo/index.php
index 0b8d59a9..f531fcb2 100755
--- a/demo/index.php
+++ b/demo/index.php
@@ -83,12 +83,12 @@ interface so that you can see how everything flows together.

Learn how to integrate PayPal Checkout w/ Line Items using PayPal's REST API v2. It allows you to create and capture an order using the Orders API.

- Launch Demo + Launch Demo $sandbox, + 'PayPalAPIMode' => $api_mode, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$orderId = isset($_GET['token']) ? $_GET['token'] : ''; + +$PayPalResult = $PayPal->captureOrder($orderId); + +if ($PayPalResult['success']) { + $_SESSION['paypal_transaction_id'] = isset($PayPalResult['capture_id']) ? $PayPalResult['capture_id'] : ''; + + // Get payment info + $payment_captures = isset($PayPalResult['purchase_units'][0]['payments']['captures']) ? $PayPalResult['purchase_units'][0]['payments']['captures'] : []; + $_SESSION['paypal_fee'] = isset($payment_captures[0]['seller_receivable_breakdown']['paypal_fee']['value']) ? $payment_captures[0]['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; + + header('Location: order-complete.php'); + exit; +} else { + $_SESSION['paypal_errors'] = $PayPalResult['error']; + header('Location: ../../error.php'); +} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php b/demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php new file mode 100644 index 00000000..f46968a7 --- /dev/null +++ b/demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php @@ -0,0 +1,92 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$orderId = isset($_GET['token']) ? $_GET['token'] : ''; + +$PayPalResult = $PayPal->getOrder($orderId); + +/** + * Now we'll check for any errors returned by PayPal, and if we get an error, + * we'll save the error details to a session and redirect the user to an + * error page to display it accordingly. + * + * If the call is successful, we'll save some data we might want to use + * later into session variables. + */ +if($PayPalResult['success']) { + $_SESSION['order_id'] = $orderId; + + // Get order details + $order = $PayPalResult['order']; + + // Basic Payer Info + $_SESSION['paypal_payer_id'] = isset($order['payer']['payer_id']) ? $order['payer']['payer_id'] : ''; + $_SESSION['phone_number'] = isset($order['payer']['phone']['phone_number']['national_number']) ? $order['payer']['phone']['phone_number']['national_number'] : ''; + $_SESSION['email'] = isset($order['payer']['email_address']) ? $order['payer']['email_address'] : ''; + $_SESSION['first_name'] = isset($order['payer']['name']['given_name']) ? $order['payer']['name']['given_name'] : ''; + $_SESSION['last_name'] = isset($order['payer']['name']['surname']) ? $order['payer']['name']['surname'] : ''; + $_SESSION['billing_country_code'] = isset($order['payer']['address']['country_code']) ? $order['payer']['address']['country_code'] : ''; + + // Shipping Address + $purchaseUnit = $order['purchase_units'][0]; + $shipping = isset($purchaseUnit['shipping']) ? $purchaseUnit['shipping'] : []; + + $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; + $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; + $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; + $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; + $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; + $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; + $_SESSION['shipping_country_name'] = 'United States'; // For demo purposes, we are assuming US. In real app, map country code to country name. + + /** + * At this point, we now have the buyer's shipping address available in our app. + * We could now run the data through a shipping calculator to retrieve rate + * information for this particular order. + * + * This would also be the time to calculate any sales tax you may need to + * add to the order, as well as handling fees. + * + * We're going to set static values for these things in our static + * shopping cart, and then re-calculate our grand total. + */ + $_SESSION['shopping_cart']['shipping'] = 10.00; + $_SESSION['shopping_cart']['handling'] = 2.50; + $_SESSION['shopping_cart']['tax'] = 1.50; + + $_SESSION['shopping_cart']['grand_total'] = number_format( + $_SESSION['shopping_cart']['subtotal'] + + $_SESSION['shopping_cart']['shipping'] + + $_SESSION['shopping_cart']['handling'] + + $_SESSION['shopping_cart']['tax'],2); + + /** + * Now we will redirect the user to a final review + * page so they can see the shipping/handling/tax + * that has been added to the order. + */ + header('Location: review.php'); + exit; +} else { + $_SESSION['paypal_errors'] = $PayPalResult['error']; + header('Location: ../../error.php'); +} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php b/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php new file mode 100644 index 00000000..6767ec64 --- /dev/null +++ b/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php @@ -0,0 +1,83 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +// Build PayPal order data from session +$orderData = [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ + [ + 'amount' => [ + 'currency_code' => 'USD', + 'value' => $_SESSION['shopping_cart']['grand_total'], + 'breakdown' => [ + 'item_total' => [ + 'currency_code' => 'USD', + 'value' => number_format($_SESSION['shopping_cart']['subtotal'], 2, '.', '') + ], + 'shipping' => [ + 'currency_code' => 'USD', + 'value' => number_format($_SESSION['shopping_cart']['shipping'], 2, '.', '') + ], + 'handling' => [ + 'currency_code' => 'USD', + 'value' => number_format($_SESSION['shopping_cart']['handling'], 2, '.', '') + ], + 'tax_total' => [ + 'currency_code' => 'USD', + 'value' => number_format($_SESSION['shopping_cart']['tax'], 2, '.', '') + ], + ], + ], + 'items' => array_map(function($item) { + return [ + 'name' => $item['name'], + 'sku' => $item['id'], + 'quantity' => (string)$item['qty'], + 'unit_amount' => [ + 'currency_code' => 'USD', + 'value' => number_format($item['price'], 2, '.', '') + ] + ]; + }, $_SESSION['shopping_cart']['items']), + ], + ], + 'application_context' => [ + 'brand_name' => 'Angell EYE', + 'landing_page' => 'BILLING', // or 'LOGIN' + 'user_action' => 'CONTINUE', + 'return_url' => $domain . 'demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php', + 'cancel_url' => $domain . 'demo/rest/rest-checkout-line-items-v2/', + ], +]; + +$PaymentResult = $PayPal->createOrder($orderData); + +if ($PaymentResult['success']) { + // Redirect to PayPal approval URL + header('Location: ' . $PaymentResult['approval_url']); + exit; +} else { + // Handle error + echo '

';
+    print_r($PaymentResult['error']);
+    echo '
'; +} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/index.php b/demo/rest/rest-checkout-line-items-v2/index.php new file mode 100644 index 00000000..3c5d0f4a --- /dev/null +++ b/demo/rest/rest-checkout-line-items-v2/index.php @@ -0,0 +1,142 @@ + '123-ABC', + 'name' => 'Widget', + 'qty' => '2', + 'price' => '9.99', +); + +$_SESSION['items'][1] = array( + 'id' => 'XYZ-456', + 'name' => 'Gadget', + 'qty' => '1', + 'price' => '4.99', +); +$_SESSION['shopping_cart'] = array( + 'items' => $_SESSION['items'], + 'subtotal' => 24.97, + 'shipping' => 0, + 'handling' => 0, + 'tax' => 0, +); +$_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'],2); +?> + + + + PayPal Checkout with Line Items | PHP Class Library | Angell EYE + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +

Shopping Cart


+

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any + billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal + after the user logs in and is returned back to the site.

+

To complete the demo, click the Checkout with PayPal button and use the following credentials to login to PayPal.

+ Email Address: paypal-buyer@angelleye.com
+ Password: paypalphp +

+ + + + + + + + + + + + + + + + + + + + + +
IDNamePriceQTYTotal
$ $
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
+
+
+
+
+
+ + \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/order-complete.php b/demo/rest/rest-checkout-line-items-v2/order-complete.php new file mode 100644 index 00000000..251c295d --- /dev/null +++ b/demo/rest/rest-checkout-line-items-v2/order-complete.php @@ -0,0 +1,138 @@ + + + + + PayPal Checkout with Line Items | Order Complete | PHP Class Library | Angell EYE + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +

Payment Complete!


+

+ We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID + to the Billing Information, which was provided in the captureOrder response. +

+ + + + + + + + + + + + + + + + + + + + + +
IDNamePriceQTYTotal
$ $
+
+
+

Billing Information

+

+ ' : ''); + echo (!empty($_SESSION['email']) ? $_SESSION['email'] . '
' : ''); + echo (!empty($_SESSION['phone_number']) ? $_SESSION['phone_number'] . '
' : ''); + echo (!empty($_SESSION['paypal_transaction_id']) ? $_SESSION['paypal_transaction_id'] : ''); + ?> +

+
+
+

Shipping Information

+

+ ' : ''); + echo (!empty($_SESSION['shipping_street']) ? $_SESSION['shipping_street'] . '
' : ''); + echo (!empty($_SESSION['shipping_city']) ? $_SESSION['shipping_city'] . ', ' : ''); + echo (!empty($_SESSION['shipping_state']) ? $_SESSION['shipping_state'] . ' ' : ''); + echo (!empty($_SESSION['shipping_zip']) ? $_SESSION['shipping_zip'] . '
' : ''); + echo (!empty($_SESSION['shipping_country_name']) ? $_SESSION['shipping_country_name'] : ''); + ?> +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
 
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/review.php b/demo/rest/rest-checkout-line-items-v2/review.php new file mode 100644 index 00000000..ca8ec1ba --- /dev/null +++ b/demo/rest/rest-checkout-line-items-v2/review.php @@ -0,0 +1,135 @@ + + + + + PayPal Checkout with Line Items | Order Review | PHP Class Library | Angell EYE + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +

Order Review


+

Display the final review page to the buyer using the details retrieved from the Get Order response — including shipping, handling, tax, and buyer-provided billing/shipping information. +

+

+ The payment has not been processed at this point because we have not yet called the final captureOrder API. That is what will happen when we click the "Complete Order" button below. +

+ + + + + + + + + + + + + + + + + + + + + +
IDNamePriceQTYTotal
$ $
+
+
+

Billing Information

+

+ ' : ''); + echo (!empty($_SESSION['email']) ? $_SESSION['email'] . '
' : ''); + echo (!empty($_SESSION['phone_number']) ? $_SESSION['phone_number'] . '' : ''); + ?> +

+
+
+

Shipping Information

+

+ ' : ''); + echo (!empty($_SESSION['shipping_street']) ? $_SESSION['shipping_street'] . '
' : ''); + echo (!empty($_SESSION['shipping_city']) ? $_SESSION['shipping_city'] . ', ' : ''); + echo (!empty($_SESSION['shipping_state']) ? $_SESSION['shipping_state'] . ' ' : ''); + echo (!empty($_SESSION['shipping_zip']) ? $_SESSION['shipping_zip'] . '
' : ''); + echo (!empty($_SESSION['shipping_country_name']) ? $_SESSION['shipping_country_name'] : ''); + ?> +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
Complete Order
+
+
+
+
+
+ + \ No newline at end of file diff --git a/samples/classic/SetExpressCheckout.php b/samples/classic/SetExpressCheckout.php index 03c961c4..afd75ed6 100644 --- a/samples/classic/SetExpressCheckout.php +++ b/samples/classic/SetExpressCheckout.php @@ -22,8 +22,8 @@ $SECFields = array( 'token' => '', // A timestamped token, the value of which was returned by a previous SetExpressCheckout call. 'maxamt' => '200.00', // The expected maximum total amount the order will be, including S&H and sales tax. - 'returnurl' => 'http://localhost:8888/paypal-library/samples/classic/DoExpressCheckoutPayment.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. - 'cancelurl' => $domain . 'paypal/class/cancel.php', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'returnurl' => $domain . 'samples/classic/DoExpressCheckoutPayment.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => $domain . 'samples/classic/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. 'callback' => '', // URL to which the callback request from PayPal is sent. Must start with https:// for production. 'callbacktimeout' => '', // An override for you to request more or less time to be able to process the callback request and response. Acceptable range for override is 1-6 seconds. If you specify greater than 6 PayPal will use default value of 3 seconds. 'callbackversion' => '', // The version of the Instant Update API you're using. The default is the current version. diff --git a/samples/rest/DoExpressCheckoutPayment.php b/samples/rest/DoExpressCheckoutPayment.php index ed69d3c2..e30f7527 100644 --- a/samples/rest/DoExpressCheckoutPayment.php +++ b/samples/rest/DoExpressCheckoutPayment.php @@ -14,13 +14,9 @@ $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); -$PayPalRequestedData = array( - 'paymentID' => isset($_GET['paymentId']) ? $_GET['paymentId'] : '', - 'token' => isset($_GET['token']) ? $_GET['token'] : '', - 'PayerID' => isset($_GET['PayerID']) ? $_GET['PayerID'] : '', -); +$orderId = isset($_GET['token']) ? $_GET['token'] : ''; -$ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData); +$PaymentResult = $PayPal->captureOrder($orderId); echo '
';
-print_r($ExecuteResult);
\ No newline at end of file
+print_r($PaymentResult);
\ No newline at end of file
diff --git a/samples/rest/SetExpressCheckout.php b/samples/rest/SetExpressCheckout.php
index d85f4ec9..edcc0c74 100644
--- a/samples/rest/SetExpressCheckout.php
+++ b/samples/rest/SetExpressCheckout.php
@@ -18,176 +18,51 @@
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
-$SECFields = array(
-	'token' => '', 								// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
-	'maxamt' => '200.00', 							// The expected maximum total amount the order will be, including S&H and sales tax.
-	'returnurl' => 'http://localhost:8888/paypal-library/samples/rest/DoExpressCheckoutPayment.php', 	// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
-	'cancelurl' => $domain . 'paypal/class/cancel.php', 			// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
-	'callback' => '', 							// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
-	'callbacktimeout' => '', 						// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
-	'callbackversion' => '', 						// The version of the Instant Update API you're using.  The default is the current version.							
-	'reqconfirmshipping' => '0', 						// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
-	'noshipping' => '1', 							// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
-	'addroverride' => '', 							// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
-	'localecode' => '', 							// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
-	'pagestyle' => '', 							// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
-	'hdrimg' => '', 							// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
-	'hdrbordercolor' => '', 						// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
-	'hdrbackcolor' => '', 							// Sets the background color for the header of the payment page.  Default is white.  
-	'payflowcolor' => '', 							// Sets the background color for the payment page.  Default is white.
-	'skipdetails' => '', 							// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
-	'email' => '', 								// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
-	'solutiontype' => 'Sole', 						// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
-	'landingpage' => 'Billing', 						// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
-	'channeltype' => '', 							// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
-	'giropaysuccessurl' => '', 						// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
-	'giropaycancelurl' => '', 						// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
-	'banktxnpendingurl' => '',  						// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
-	'brandname' => 'Angell EYE', 						// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
-	'customerservicenumber' => '555-555-5555', 				// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
-	'giftmessageenable' => '1', 						// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
-	'giftreceiptenable' => '1', 						// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
-	'giftwrapenable' => '1', 						// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
-	'giftwrapname' => 'Box with Ribbon', 					// Label for the gift wrap option such as "Box with ribbon".  25 char max.
-	'giftwrapamount' => '2.50', 						// Amount charged for gift-wrap service.
-	'buyeremailoptionenable' => '1', 					// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
-	'surveyquestion' => '', 						// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
-	'surveyenable' => '1', 							// Enable survey functionality. Allowable values are 0 and 1
-	'buyerid' => '', 							// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
-	'buyerusername' => '', 							// The user name of the user at the marketplaces site.
-	'buyerregistrationdate' => '2012-07-14T00:00:00Z',  			// Date when the user registered with the marketplace.
-	'allowpushfunding' => ''						// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
-);
-
-// Basic array of survey choices.  Nothing but the values should go in here.  
-$SurveyChoices = array('Yes', 'No');
-
-$Payments = array();
-$Payment = array(
-	'amt' => '100.00', 									// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
-	'currencycode' => 'USD', 								// A three-character currency code.  Default is USD.
-	'itemamt' => '80.00', 									// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
-	'shippingamt' => '15.00', 								// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
-	'insuranceoptionoffered' => '', 							// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
-	'handlingamt' => '', 									// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
-	'taxamt' => '5.00', 									// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
-	'desc' => 'This is a test order.', 							// Description of items on the order.  127 char max.
-	'custom' => '', 									// Free-form field for your own use.  256 char max.
-	'invnum' => '', 									// Your own invoice or tracking number.  127 char max.
-	'notifyurl' => '',  									// URL for receiving Instant Payment Notifications
-	'shiptoname' => '', 									// Required if shipping is included.  Person's name associated with this address.  32 char max.
-	'shiptostreet' => '', 									// Required if shipping is included.  First street address.  100 char max.
-	'shiptostreet2' => '', 									// Second street address.  100 char max.
-	'shiptocity' => '', 									// Required if shipping is included.  Name of city.  40 char max.
-	'shiptostate' => '', 									// Required if shipping is included.  Name of state or province.  40 char max.
-	'shiptozip' => '', 									// Required if shipping is included.  Postal code of shipping address.  20 char max.
-	'shiptocountry' => '', 									// Required if shipping is included.  Country code of shipping address.  2 char max.
-	'shiptophonenum' => '',  								// Phone number for shipping address.  20 char max.
-	'notetext' => 'This is a test note before ever having left the web site.', 		// Note to the merchant.  255 char max.  
-	'allowedpaymentmethod' => '', 								// The payment method type.  Specify the value InstantPaymentOnly.
-	'paymentaction' => 'Sale', 								// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
-	'paymentrequestid' => '',  								// A unique identifier of the specific payment request, which is required for parallel payments. 
-	'sellerpaypalaccountid' => ''								// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
-);
-				
-$PaymentOrderItems = array();
-$Item = array(
-	'name' => 'Widget 123', 					// Item name. 127 char max.
-	'desc' => 'Widget 123', 					// Item description. 127 char max.
-	'amt' => '40.00', 						// Cost of item.
-	'number' => '123', 						// Item number.  127 char max.
-	'qty' => '1', 							// Item qty on order.  Any positive integer.
-	'taxamt' => '', 						// Item sales tax
-	'itemurl' => 'http://www.angelleye.com/products/123.php',	// URL for the item.
-	'itemcategory' => '', 						// One of the following values:  Digital, Physical
-	'itemweightvalue' => '', 					// The weight value of the item.
-	'itemweightunit' => '', 					// The weight unit of the item.
-	'itemheightvalue' => '', 					// The height value of the item.
-	'itemheightunit' => '', 					// The height unit of the item.
-	'itemwidthvalue' => '', 					// The width value of the item.
-	'itemwidthunit' => '', 						// The width unit of the item.
-	'itemlengthvalue' => '', 					// The length value of the item.
-	'itemlengthunit' => '',  					// The length unit of the item.
-	'ebayitemnumber' => '', 					// Auction item number.  
-	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
-	'ebayitemorderid' => '',  					// Auction order ID number.
-	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
-);
-array_push($PaymentOrderItems, $Item);
+$orderData = [
+	'intent' => 'CAPTURE', // or 'AUTHORIZE' if you plan to capture later
+   	'purchase_units' => [
+		[
+			'reference_id' => 'ORDER-' . uniqid(),
+			'amount' => [
+				'currency_code' => 'USD',
+				'value' => '50.00',
+				'breakdown' => [
+					'item_total' => [
+						'currency_code' => 'USD',
+						'value' => '50.00'
+					]
+				]
+			],
+			'items' => [
+				[
+					'name' => 'Sample Product',
+					'unit_amount' => [
+						'currency_code' => 'USD',
+						'value' => '25.00'
+					],
+					'quantity' => '2'
+				]
+			]
+		]
+    	],
+	'application_context' => [
+		'brand_name' => 'Angell EYE',
+		'landing_page' => 'LOGIN', // or 'BILLING' for guest checkout
+		'user_action' => 'CONTINUE',
+		'return_url' => $domain . 'samples/rest/DoExpressCheckoutPayment.php',
+		'cancel_url' => $domain . 'samples/rest/', 
+	]
+];
 
-$Item = array(
-	'name' => 'Widget 456', 					// Item name. 127 char max.
-	'desc' => 'Widget 456', 					// Item description. 127 char max.
-	'amt' => '40.00', 						// Cost of item.
-	'number' => '456', 						// Item number.  127 char max.
-	'qty' => '1', 							// Item qty on order.  Any positive integer.
-	'taxamt' => '', 						// Item sales tax
-	'itemurl' => 'http://www.angelleye.com/products/456.php', 	// URL for the item.
-	'itemcategory' => 'Digital', 					// One of the following values:  Digital, Physical
-	'itemweightvalue' => '', 					// The weight value of the item.
-	'itemweightunit' => '', 					// The weight unit of the item.
-	'itemheightvalue' => '', 					// The height value of the item.
-	'itemheightunit' => '', 					// The height unit of the item.
-	'itemwidthvalue' => '', 					// The width value of the item.
-	'itemwidthunit' => '', 						// The width unit of the item.
-	'itemlengthvalue' => '', 					// The length value of the item.
-	'itemlengthunit' => '',  					// The length unit of the item.
-	'ebayitemnumber' => '', 					// Auction item number.  
-	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
-	'ebayitemorderid' => '',  					// Auction order ID number.
-	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
-);
-array_push($PaymentOrderItems, $Item);
+$PaymentResult = $PayPal->createOrder($orderData);
 
-$Payment['order_items'] = $PaymentOrderItems;
-array_push($Payments, $Payment);
+if ($PaymentResult['success']) {
+	$_SESSION['paypal_order_id'] = $PaymentResult['order_id'];
 
-$BuyerDetails = array(
-	'buyerid' => '', 		// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
-	'buyerusername' => '', 		// The username of the marketplace site.
-	'buyerregistrationdate' => ''	// The registration of the buyer with the marketplace.
-);
-						
-// For shipping options we create an array of all shipping choices similar to how order items works.
-$ShippingOptions = array();
-$Option = array(
-	'l_shippingoptionisdefault' => '', 		// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
-	'l_shippingoptionname' => '', 			// Shipping option name.  Required if specifying the Callback URL.  50 character max.
-	'l_shippingoptionlabel' => '', 			// Shipping option label.  Required if specifying the Callback URL.  50 character max.
-	'l_shippingoptionamount' => '' 			// Shipping option amount.  Required if specifying the Callback URL.  
-);
-array_push($ShippingOptions, $Option);
-		
-$BillingAgreements = array();
-$Item = array(
-	'l_billingtype' => 'MerchantInitiatedBilling', 				// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
-	'l_billingagreementdescription' => 'Billing Agreement', 		// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
-	'l_paymenttype' => 'Any', 						// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
-	'l_billingagreementcustom' => ''					// Custom annotation field for your own use.  256 char max.
-);
-array_push($BillingAgreements, $Item);
-
-$PayPalRequest = array(
-	'SECFields' => $SECFields, 
-	'SurveyChoices' => $SurveyChoices, 
-	'BillingAgreements' => $BillingAgreements, 
-	'Payments' => $Payments
-);
-
-$PaymentResult = $PayPal->CreatePayment($PayPalRequest);
-
-// Save approval URL to session
-$_SESSION['PayPalPaymentID'] = $PaymentResult['RESPONSE']['id'];
-
-// Redirect user to PayPal approval URL
-$ApprovalUrl = '';
-foreach ($PaymentResult['RESPONSE']['links'] as $link) {
-    if ($link['rel'] === 'approval_url') {
-        $ApprovalUrl = $link['href'];
-        break;
-    }
+	echo 'Click here to continue.

'; + + echo '
';
+	print_r($PaymentResult);
+} else {
+    	echo 'Error creating order: ' . $PaymentResult['error'];
 }
-
-echo 'Click here to continue.

'; -echo '
';
-print_r($PaymentResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index c7c09627..99d4705c 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -508,108 +508,6 @@ private function getApprovalUrl($links)
         return null;
     }
 
-    public function CreatePayment($paymentData) {
-        $paymentsMappedData = [];
-
-        // Map basic payment info
-        $paymentsMappedData['intent'] = strtolower($paymentData['Payments'][0]['paymentaction'] ?? 'sale');
-        $paymentsMappedData['payer'] = [
-            'payment_method' => 'paypal'
-        ];
-
-        // Redirect URLs
-        $paymentsMappedData['redirect_urls'] = [
-            'return_url' => $paymentData['SECFields']['returnurl'] ?? '',
-            'cancel_url' => $paymentData['SECFields']['cancelurl'] ?? ''
-        ];
-
-        // Transaction
-        $transaction = [
-            'amount' => [
-                'total' => $paymentData['Payments'][0]['amt'] ?? '0.00',
-                'currency' => $paymentData['Payments'][0]['currencycode'] ?? 'USD',
-                'details' => [
-                    'subtotal' => $paymentData['Payments'][0]['itemamt'] ?? '0.00',
-                    'tax' => $paymentData['Payments'][0]['taxamt'] ?? '0.00',
-                    'shipping' => $paymentData['Payments'][0]['shippingamt'] ?? '0.00'
-                ]
-            ],
-            'description' => $paymentData['Payments'][0]['desc'] ?? '',
-            'item_list' => [
-                'items' => []
-            ]
-        ];
-
-        // Map order items
-        if (!empty($paymentData['Payments'][0]['order_items'])) {
-            foreach ($paymentData['Payments'][0]['order_items'] as $item) {
-                $transaction['item_list']['items'][] = [
-                    'name' => $item['name'] ?? '',
-                    'sku' => $item['number'] ?? '',
-                    'price' => $item['amt'] ?? '0.00',
-                    'currency' => $paymentData['Payments'][0]['currencycode'] ?? 'USD',
-                    'quantity' => $item['qty'] ?? 1
-                ];
-            }
-        }
-
-        $paymentsMappedData['transactions'][] = $transaction;
-        
-        $response = $this->makeRequest('/v1/payments/payment', 'POST', $paymentsMappedData);
-
-        $responseSimplified = [];
-
-        // Handle Response
-        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
-            $responseSimplified = array(
-                'SUCCESS' => true,
-                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
-                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
-                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
-            );
-        } else {
-            $responseSimplified = array(
-                'SUCCESS' => false,
-                'STATUSCODE' => $response['status_code'],
-                'ERRORS' => !empty($response['body']) ? $response['body'] : ['invalid_payment' => 'Payment execution failed'],
-                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
-            );
-        }
-
-        return $responseSimplified;
-    }
-
-    public function ExecutePayment($paymentData) {
-        $data = [
-            'payer_id' => !empty($paymentData['PayerID']) ? $paymentData['PayerID'] : ''
-        ];
-
-        $paymentID = !empty($paymentData['paymentID']) ? $paymentData['paymentID'] : '';
-
-        $response = $this->makeRequest('/v1/payments/payment/' . $paymentID . '/execute', 'POST', $data);
-        
-        $responseSimplified = [];
-
-        // Handle Response
-        if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
-            $responseSimplified = array(
-                'SUCCESS' => true,
-                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
-                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
-                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
-            );
-        } else {
-            $responseSimplified = array(
-                'SUCCESS' => false,
-                'STATUSCODE' => $response['status_code'],
-                'ERRORS' => !empty($response['body']) ? $response['body'] : ['invalid_payment' => 'Payment execution failed'],
-                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
-            );
-        }
-
-        return $responseSimplified;
-    }
-
     public function DoDirectPayment($paymentData) {
         $paymentsMappedData = [];
 
diff --git a/templates/rest/DoExpressCheckoutPayment.php b/templates/rest/DoExpressCheckoutPayment.php
index 2842e639..0d1fffb9 100644
--- a/templates/rest/DoExpressCheckoutPayment.php
+++ b/templates/rest/DoExpressCheckoutPayment.php
@@ -17,13 +17,9 @@
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
-$PayPalRequestedData = array(
-	'paymentID' => '',
-	'token' => '',
-	'PayerID' => '',
-);
+$orderId = '';
 
-$ExecuteResult = $PayPal->ExecutePayment($PayPalRequestedData);
+$PaymentResult = $PayPal->captureOrder($orderId);
 
 echo '
';
-print_r($ExecuteResult);
\ No newline at end of file
+print_r($PaymentResult);
\ No newline at end of file
diff --git a/templates/rest/SetExpressCheckout.php b/templates/rest/SetExpressCheckout.php
index ff488bb1..6ef179c1 100644
--- a/templates/rest/SetExpressCheckout.php
+++ b/templates/rest/SetExpressCheckout.php
@@ -1,185 +1,68 @@
  $sandbox,
 	'PayPalAPIMode' => $api_mode,
 	'ClientID' => $rest_client_id,
-	'ClientSecret' => $rest_client_secret, 
+	'ClientSecret' => $rest_client_secret,
+	'APIVersion' => '97.0', 
+	'APISubject' => '',
 	'PrintHeaders' => $print_headers, 
-	'LogResults' => $log_results,
+	'LogResults' => $log_results, 
 	'LogPath' => $log_path,
 );
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
-// Prepare request arrays
-$SECFields = array(
-	'token' => '', 				// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
-	'maxamt' => '', 			// The expected maximum total amount the order will be, including S&H and sales tax.
-	'returnurl' => '', 			// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
-	'cancelurl' => '', 			// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
-	'callback' => '', 			// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
-	'callbacktimeout' => '', 		// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
-	'callbackversion' => '', 		// The version of the Instant Update API you're using.  The default is the current version.							
-	'reqconfirmshipping' => '', 		// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
-	'noshipping' => '', 			// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
-	'addroverride' => '', 			// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
-	'localecode' => '', 			// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
-	'pagestyle' => '', 			// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
-	'hdrimg' => '', 			// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
-	'hdrbordercolor' => '', 		// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
-	'hdrbackcolor' => '', 			// Sets the background color for the header of the payment page.  Default is white.  
-	'payflowcolor' => '', 			// Sets the background color for the payment page.  Default is white.
-	'cartbordercolor' => '', 		// The HTML hex code for your principal identifying color.  PayPal blends your color to white in a gradient fill that borders the cart review area of the PayPal checkout user interface.  6 single-byte hexadecimal chars. that represent an HTML hex code for a color.
-	'logoimg' => '', 			// A URL to your logo image.  Formats:  .gif, .jpg, .png.  190x60.  PayPal places your logo image at the top of the cart review area.  This logo needs to be stored on a https:// server.
-	'skipdetails' => '', 			// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
-	'email' => '', 				// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
-	'solutiontype' => '', 			// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
-	'landingpage' => '', 			// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
-	'channeltype' => '', 			// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
-	'giropaysuccessurl' => '', 		// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
-	'giropaycancelurl' => '', 		// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
-	'banktxnpendingurl' => '',  		// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
-	'brandname' => '', 			// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
-	'customerservicenumber' => '', 		// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
-	'giftmessageenable' => '', 		// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
-	'giftreceiptenable' => '', 		// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
-	'giftwrapenable' => '', 		// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
-	'giftwrapname' => '', 			// Label for the gift wrap option such as "Box with ribbon".  25 char max.
-	'giftwrapamount' => '', 		// Amount charged for gift-wrap service.
-	'buyeremailoptionenable' => '', 	// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
-	'surveyquestion' => '', 		// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
-	'surveyenable' => '', 			// Enable survey functionality. Allowable values are 0 and 1
-	'totaltype' => '', 			// Enables display of "estimated total" instead of "total" in the cart review area.  Values are:  Total, EstimatedTotal
-	'notetobuyer' => '', 			// Displays a note to buyers in the cart review area below the total amount.  Use the note to tell buyers about items in the cart, such as your return policy or that the total excludes shipping and handling.  127 char max.
-	'buyerid' => '', 			// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
-	'buyerusername' => '', 			// The user name of the user at the marketplaces site.
-	'buyerregistrationdate' => '',  	// Date when the user registered with the marketplace.
-	'allowpushfunding' => '', 		// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
-	'userselectedfundingsource' => '', 	// This element could be used to specify the preferred funding option for a guest user.  However, the LANDINGPAGE element must also be set to Billing.  Otherwise, it is ignored.  Values:  BML, ChinaUnionPay, CreditCard, ELV, Finance, QIWI
-	'taxidtype' => '', 			// The buyer's tax ID type.  This field is required for Brazil and used for Brazil only.  Values:  BR_CPF for individuals and BR_CNPJ for businesses.
-	'taxid' => ''				// The buyer's tax ID.  This field is required for Brazil and used for Brazil only.  The tax ID is 11 single-byte characters for individutals and 14 single-byte characters for businesses.
-);
-
-// Basic array of survey choices.  Nothing but the values should go in here.  
-$SurveyChoices = array('Choice 1', 'Choice2', 'Choice3', 'etc');
+$orderData = [
+	'intent' => 'CAPTURE', // or 'AUTHORIZE' if you plan to capture later
+   	'purchase_units' => [
+		[
+			'reference_id' => '',
+			'amount' => [
+				'currency_code' => '',
+				'value' => '',
+				'breakdown' => [
+					'item_total' => [
+						'currency_code' => '',
+						'value' => ''
+					]
+				]
+			],
+			'items' => [
+				[
+					'name' => '',
+					'unit_amount' => [
+						'currency_code' => '',
+						'value' => ''
+					],
+					'quantity' => ''
+				]
+			]
+		]
+    	],
+	'application_context' => [
+		'brand_name' => '',
+		'landing_page' => 'LOGIN', // or 'BILLING' for guest checkout
+		'user_action' => 'CONTINUE',
+		'return_url' => $domain . 'samples/rest/DoExpressCheckoutPayment.php',
+		'cancel_url' => $domain . 'samples/rest/', 
+	]
+];
 
-$Payments = array();
-$Payment = array(
-    'amt' => '', 			// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
-    'currencycode' => '', 		// A three-character currency code.  Default is USD.
-    'itemamt' => '', 			// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
-    'shippingamt' => '', 		// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
-    'shipdiscamt' => '', 		// Shipping discount for this order, specified as a negative number.
-    'insuranceamt' => '', 		// Total shipping insurance costs for this order.
-    'insuranceoptionoffered' => '', 	// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
-    'handlingamt' => '', 		// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
-    'taxamt' => '', 			// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
-    'desc' => '', 			// Description of items on the order.  127 char max.
-    'custom' => '', 			// Free-form field for your own use.  256 char max.
-    'invnum' => '', 			// Your own invoice or tracking number.  127 char max.
-    'notifyurl' => '', 			// URL for receiving Instant Payment Notifications
-    'multishipping' => '', 		// The value 1 indicates that this payment is associated with multiple shipping addresses.
-    'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
-    'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
-    'shiptostreet2' => '', 		// Second street address.  100 char max.
-    'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
-    'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
-    'shiptozip' => '', 			// Required if shipping is included.  Postal code of shipping address.  20 char max.
-    'shiptocountrycode' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
-    'shiptophonenum' => '',  		// Phone number for shipping address.  20 char max.
-    'notetext' => '', 			// Note to the merchant.  255 char max.
-    'allowedpaymentmethod' => '', 	// The payment method type.  Specify the value InstantPaymentOnly.
-    'paymentaction' => '', 		// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order.
-    'paymentrequestid' => '',  		// A unique identifier of the specific payment request, which is required for parallel payments.
-    'sellerpaypalaccountid' => '',	// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
-    'transactionid' => '',		// Transaction ID number of the transaction that was created.  You can specify up to 10 payments.
-    'bucketcategorytype' => '',         // The category of a payment.  Values are:  1 - International shipping, 2 - Local delivery, 3 - BOPIS (Buy online pick-up in store), 4 - PUDO (Pick up drop off)
-    'location_type' => '',              // The type of merchant location.  Set this field if the items purchased will not be shipped, such as, BOPIS transactions.  Values are: 1 - Consumer, 2 - Store, for BOPIS transactions, 3 - PUDO
-    'location_id' => '',                // The Location ID specified by the merchant for BOPIS or PUDO transactions.
-);
-				
-$PaymentOrderItems = array();
-$Item = array(
-	'name' => '', 				// Item name. 127 char max.
-	'desc' => '', 				// Item description. 127 char max.
-	'amt' => '', 				// Cost of item.
-	'number' => '', 			// Item number.  127 char max.
-	'qty' => '', 				// Item qty on order.  Any positive integer.
-	'taxamt' => '', 			// Item sales tax
-	'itemurl' => '', 			// URL for the item.
-	'itemcategory' => '', 			// One of the following values:  Digital, Physical
-	'itemweightvalue' => '', 		// The weight value of the item.
-	'itemweightunit' => '', 		// The weight unit of the item.
-	'itemheightvalue' => '', 		// The height value of the item.
-	'itemheightunit' => '', 		// The height unit of the item.
-	'itemwidthvalue' => '', 		// The width value of the item.
-	'itemwidthunit' => '', 			// The width unit of the item.
-	'itemlengthvalue' => '', 		// The length value of the item.
-	'itemlengthunit' => '',  		// The length unit of the item.
-	'ebayitemnumber' => '', 		// Auction item number.  
-	'ebayitemauctiontxnid' => '', 		// Auction transaction ID number.  
-	'ebayitemorderid' => '',  		// Auction order ID number.
-	'ebayitemcartid' => ''			// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
-);
-array_push($PaymentOrderItems, $Item);
-$Payment['order_items'] = $PaymentOrderItems;
+$PaymentResult = $PayPal->createOrder($orderData);
 
-array_push($Payments, $Payment);
+if ($PaymentResult['success']) {
+	$_SESSION['paypal_order_id'] = $PaymentResult['order_id'];
 
-$BuyerDetails = array(
-	'buyerid' => '', 			// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
-	'buyerusername' => '', 			// The username of the marketplace site.
-	'buyerregistrationdate' => ''		// The registration of the buyer with the marketplace.
-);
-						
-// For shipping options we create an array of all shipping choices similar to how order items works.
-$ShippingOptions = array();
-$Option = array(
-	'l_shippingoptionisdefault' => '', 	// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
-	'l_shippingoptionname' => '', 		// Shipping option name.  Required if specifying the Callback URL.  50 character max.
-	'l_shippingoptionlabel' => '', 		// Shipping option label.  Required if specifying the Callback URL.  50 character max.
-	'l_shippingoptionamount' => '' 		// Shipping option amount.  Required if specifying the Callback URL.  
-);
-array_push($ShippingOptions, $Option);
-		
-$BillingAgreements = array();
-$Item = array(
-	'l_billingtype' => '', 				// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
-	'l_billingagreementdescription' => '', 		// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
-	'l_paymenttype' => '', 				// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
-	'l_billingagreementcustom' => ''		// Custom annotation field for your own use.  256 char max.
-);
-
-array_push($BillingAgreements, $Item);
-
-$PayPalRequestData = array(
-	'SECFields' => $SECFields, 
-	'SurveyChoices' => $SurveyChoices, 
-	'Payments' => $Payments, 
-	'BuyerDetails' => $BuyerDetails, 
-	'ShippingOptions' => $ShippingOptions, 
-	'BillingAgreements' => $BillingAgreements
-);
-
-$PaymentResult = $PayPal->CreatePayment($PayPalRequestData);
-
-// Save approval URL to session
-$_SESSION['PayPalPaymentID'] = $PaymentResult['RESPONSE']['id'];
-
-// Redirect user to PayPal approval URL
-$ApprovalUrl = '';
-foreach ($PaymentResult['RESPONSE']['links'] as $link) {
-    if ($link['rel'] === 'approval_url') {
-        $ApprovalUrl = $link['href'];
-        break;
-    }
+	echo 'Click here to continue.

'; + + echo '
';
+	print_r($PaymentResult);
+} else {
+    	echo 'Error creating order: ' . $PaymentResult['error'];
 }
-
-echo 'Click here to continue.

'; -echo '
';
-print_r($PaymentResult);
\ No newline at end of file

From 88763a0cfdc6c33dff00d1d2573dbdef0c825fe4 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Fri, 31 Oct 2025 14:52:31 +0530
Subject: [PATCH 019/146] Completed ExpressCheckout Payment Flow Demo with
 Toggle of Capture and Authorize both Way Sync

---
 .../CapturePayment.php                        | 40 ++++++++++
 .../DoExpressCheckoutPayment.php              | 39 ---------
 .../ProcessPayments.php                       | 56 +++++++++++++
 .../SetExpressCheckout.php                    |  4 +-
 .../rest-checkout-line-items-v2/index.php     | 79 ++++++++++++-------
 .../rest-checkout-line-items-v2/review.php    | 20 ++++-
 src/angelleye/PayPal/PayPalREST.php           | 61 ++++++++++++++
 7 files changed, 228 insertions(+), 71 deletions(-)
 create mode 100644 demo/rest/rest-checkout-line-items-v2/CapturePayment.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/DoExpressCheckoutPayment.php
 create mode 100644 demo/rest/rest-checkout-line-items-v2/ProcessPayments.php

diff --git a/demo/rest/rest-checkout-line-items-v2/CapturePayment.php b/demo/rest/rest-checkout-line-items-v2/CapturePayment.php
new file mode 100644
index 00000000..d71585f0
--- /dev/null
+++ b/demo/rest/rest-checkout-line-items-v2/CapturePayment.php
@@ -0,0 +1,40 @@
+ $sandbox,
+        'PayPalAPIMode' => $api_mode,
+        'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+        'PrintHeaders' => $print_headers,
+        'LogResults' => $log_results,
+        'LogPath' => $log_path,
+);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$authorizationId = isset($_SESSION['authorization_id']) ? $_SESSION['authorization_id'] : '';
+
+$PayPalResult = $PayPal->captureAutorizedOrder($authorizationId);
+
+if ($PayPalResult['success']) {
+    $_SESSION['paypal_transaction_id'] = isset($PayPalResult['capture_id']) ? $PayPalResult['capture_id'] : '';
+
+    // Get payment info
+    $getOrderDetails = $PayPal->getCapturedOrderDetails($PayPalResult['capture_id']);
+
+    $_SESSION['paypal_fee'] = isset($getOrderDetails['full_response']['seller_receivable_breakdown']['paypal_fee']['value']) ? $getOrderDetails['full_response']['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00;
+
+    header('Location: order-complete.php');
+    exit;
+} else {
+    $_SESSION['paypal_errors'] = $PayPalResult['error'];
+    header('Location: ../../error.php');
+}
\ No newline at end of file
diff --git a/demo/rest/rest-checkout-line-items-v2/DoExpressCheckoutPayment.php b/demo/rest/rest-checkout-line-items-v2/DoExpressCheckoutPayment.php
deleted file mode 100644
index aee12a55..00000000
--- a/demo/rest/rest-checkout-line-items-v2/DoExpressCheckoutPayment.php
+++ /dev/null
@@ -1,39 +0,0 @@
- $sandbox,
-    'PayPalAPIMode' => $api_mode,
-    'ClientID' => $rest_client_id,
-	'ClientSecret' => $rest_client_secret,
-    'PrintHeaders' => $print_headers,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
-);
-$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
-
-$orderId = isset($_GET['token']) ? $_GET['token'] : '';
-
-$PayPalResult = $PayPal->captureOrder($orderId);
-
-if ($PayPalResult['success']) {
-    $_SESSION['paypal_transaction_id'] = isset($PayPalResult['capture_id']) ? $PayPalResult['capture_id'] : '';
-
-    // Get payment info
-    $payment_captures = isset($PayPalResult['purchase_units'][0]['payments']['captures']) ? $PayPalResult['purchase_units'][0]['payments']['captures'] : [];
-    $_SESSION['paypal_fee'] = isset($payment_captures[0]['seller_receivable_breakdown']['paypal_fee']['value']) ? $payment_captures[0]['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00;
-
-    header('Location: order-complete.php');
-    exit;
-} else {
-    $_SESSION['paypal_errors'] = $PayPalResult['error'];
-    header('Location: ../../error.php');
-}
\ No newline at end of file
diff --git a/demo/rest/rest-checkout-line-items-v2/ProcessPayments.php b/demo/rest/rest-checkout-line-items-v2/ProcessPayments.php
new file mode 100644
index 00000000..2d2727e0
--- /dev/null
+++ b/demo/rest/rest-checkout-line-items-v2/ProcessPayments.php
@@ -0,0 +1,56 @@
+ $sandbox,
+    'PayPalAPIMode' => $api_mode,
+    'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+    'PrintHeaders' => $print_headers,
+    'LogResults' => $log_results,
+    'LogPath' => $log_path,
+);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$paymentIntent = isset($_SESSION['payment_intent']) ? $_SESSION['payment_intent'] : 'CAPTURE';
+
+$orderId = isset($_GET['token']) ? $_GET['token'] : '';
+
+if ($paymentIntent === 'CAPTURE') {
+    // Capture order
+    $PayPalResult = $PayPal->captureOrder($orderId);
+
+    if ($PayPalResult['success']) {
+        $_SESSION['paypal_transaction_id'] = $PayPalResult['capture_id'] ?? '';
+        
+        $captures = $PayPalResult['purchase_units'][0]['payments']['captures'][0] ?? [];
+        $_SESSION['paypal_fee'] = $captures['seller_receivable_breakdown']['paypal_fee']['value'] ?? 0.00;
+
+        header('Location: order-complete.php');
+        exit;
+    }
+
+} else {
+    // Authorize order
+    $PayPalResult = $PayPal->authorizeOrder($orderId);
+
+    if ($PayPalResult['success']) {
+        $_SESSION['authorization_id'] = $PayPalResult['authorization_id'] ?? '';
+
+        header('Location: CapturePayment.php');
+        exit;
+    }
+}
+
+// If there’s an error in either case
+$_SESSION['paypal_errors'] = $PayPalResult['error'] ?? 'Unknown error';
+header('Location: ../../error.php');
+exit;
diff --git a/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php b/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php
index 6767ec64..9fc33484 100644
--- a/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php
+++ b/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php
@@ -20,9 +20,11 @@
 );
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
+$paymentIntent = isset($_SESSION['payment_intent']) ? $_SESSION['payment_intent'] : 'CAPTURE';
+
 // Build PayPal order data from session
 $orderData = [
-	'intent' => 'CAPTURE',
+	'intent' => $paymentIntent,
     	'purchase_units' => [
 		[
 			'amount' => [
diff --git a/demo/rest/rest-checkout-line-items-v2/index.php b/demo/rest/rest-checkout-line-items-v2/index.php
index 3c5d0f4a..dbcb712c 100644
--- a/demo/rest/rest-checkout-line-items-v2/index.php
+++ b/demo/rest/rest-checkout-line-items-v2/index.php
@@ -27,6 +27,15 @@
 	'tax' => 0,
 );
 $_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'],2);
+
+if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['checkout'])) {
+  $_SESSION['payment_intent'] = isset($_POST['payment_intent']) ? $_POST['payment_intent'] : 'CAPTURE';
+
+  // Redirect to checkout process (classic or REST)
+  header("Location: SetExpressCheckout.php");
+  exit;
+}
+
 ?>
 
   
@@ -106,33 +115,49 @@
             
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
Payment Intent + +
+ +
+
diff --git a/demo/rest/rest-checkout-line-items-v2/review.php b/demo/rest/rest-checkout-line-items-v2/review.php index ca8ec1ba..c77bf7c4 100644 --- a/demo/rest/rest-checkout-line-items-v2/review.php +++ b/demo/rest/rest-checkout-line-items-v2/review.php @@ -1,5 +1,7 @@ @@ -48,9 +50,15 @@

Order Review


Display the final review page to the buyer using the details retrieved from the Get Order response — including shipping, handling, tax, and buyer-provided billing/shipping information.

-

- The payment has not been processed at this point because we have not yet called the final captureOrder API. That is what will happen when we click the "Complete Order" button below. -

+ +

+ The payment has not been processed at this point because we have not yet called the final captureOrder API. That is what will happen when we click the "Complete Order" button below. +

+ +

+ The payment has not been captured yet because we have only created the order. Click on "Authorize & Capture Order" button below to authorize and capture the payment in one step. +

+ @@ -122,7 +130,11 @@ - +
$
Complete Order + + + +
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php index 99d4705c..e4198478 100644 --- a/src/angelleye/PayPal/PayPalREST.php +++ b/src/angelleye/PayPal/PayPalREST.php @@ -495,6 +495,67 @@ public function captureOrder($orderId) } } + /** + * Capture Authorized order + */ + public function captureAutorizedOrder($authorizationId) + { + try { + $response = $this->makeRequest('/v2/payments/authorizations/' . $authorizationId . '/capture', 'POST'); + + if ($response['status_code'] === 201) { + return [ + 'success' => true, + 'capture_id' => $response['body']['id'], + 'status' => $response['body']['status'], + 'full_response' => $response['body'] + ]; + } + + return [ + 'success' => false, + 'error' => 'Failed to capture order', + 'status_code' => $response['status_code'], + 'details' => $response['body'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } + } + + /** + * Capture Authorized order + */ + public function getCapturedOrderDetails($captureId) + { + try { + $response = $this->makeRequest('/v2/payments/captures/' . $captureId, 'GET'); + + if ($response['status_code'] === 201) { + return [ + 'success' => true, + 'status' => $response['body']['status'], + 'full_response' => $response['body'] + ]; + } + + return [ + 'success' => false, + 'error' => '', + 'status' => $response['status_code'], + 'full_response' => $response['body'] + ]; + } catch (\Exception $e) { + return [ + 'success' => false, + 'error' => $e->getMessage() + ]; + } + } + /** * Helper method to extract approval URL from links */ From ea9aa3025f9257168bc4486c76733d755b0f2f24 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 3 Nov 2025 10:39:52 +0530 Subject: [PATCH 020/146] DoReferenceTransaction Method Completed --- samples/classic/DoReferenceTransaction.php | 161 ++++++++--------- samples/rest/DoReferenceTransaction.php | 26 +++ templates/classic/DoReferenceTransaction.php | 177 ++++++++++--------- templates/rest/DoReferenceTransaction.php | 26 +++ 4 files changed, 222 insertions(+), 168 deletions(-) create mode 100644 samples/rest/DoReferenceTransaction.php create mode 100644 templates/rest/DoReferenceTransaction.php diff --git a/samples/classic/DoReferenceTransaction.php b/samples/classic/DoReferenceTransaction.php index 3af7f596..c9e665f9 100644 --- a/samples/classic/DoReferenceTransaction.php +++ b/samples/classic/DoReferenceTransaction.php @@ -3,105 +3,106 @@ require_once('../../autoload.php'); $PayPalConfig = array( - 'Sandbox' => $sandbox, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, - ); + 'Sandbox' => $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); -$PayPal = new angelleye\PayPal\PayPal($PayPalConfig); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); $DRTFields = array( - 'referenceid' => '', - 'paymentaction' => 'Sale', - 'returnfmfdetails' => '1', - 'softdescriptor' => 'Angell EYE' - ); + 'referenceid' => 'order-' . uniqid(), + 'paymentaction' => 'Sale', + 'returnfmfdetails' => '1', + 'softdescriptor' => 'Angell EYE' +); $ShippingAddress = array( - 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. - 'shiptostreet2' => '', // Second street address. 100 char max. - 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => '' // Phone number for shipping address. 20 char max. - ); + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '' // Phone number for shipping address. 20 char max. +); $PaymentDetails = array( - 'amt' => '1100.00', // Required. Total amount of the order, including shipping, handling, and tax. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - 'itemamt' => '', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. - 'shippingamt' => '', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. - 'insuranceamt' => '', - 'shippingdiscount' => '', - 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. - 'taxamt' => '', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. - 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays Yes and shows the amount. - 'desc' => 'Angell EYE Invoice - Final Payment for MiltonsBells.com', // Description of items on the order. 127 char max. - 'custom' => '', // Free-form field for your own use. 256 char max. - 'invnum' => '35', // Your own invoice or tracking number. 127 char max. - 'buttonsource' => '', // ID code for use by third-party apps to identify transactions in PayPal. - 'notifyurl' => '' // URL for receiving Instant Payment Notifications - ); + 'amt' => '1100.00', // Required. Total amount of the order, including shipping, handling, and tax. + 'currencycode' => 'USD', // A three-character currency code. Default is USD. + 'itemamt' => '', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. + 'shippingamt' => '', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'insuranceamt' => '', + 'shippingdiscount' => '', + 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => '', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays Yes and shows the amount. + 'desc' => 'Angell EYE Invoice - Final Payment for MiltonsBells.com', // Description of items on the order. 127 char max. + 'custom' => '', // Free-form field for your own use. 256 char max. + 'invnum' => '35', // Your own invoice or tracking number. 127 char max. + 'buttonsource' => '', // ID code for use by third-party apps to identify transactions in PayPal. + 'notifyurl' => '' // URL for receiving Instant Payment Notifications +); $OrderItems = array(); -$Item = array( - 'l_name' => '', // Item name. 127 char max. - 'l_description' => '', - 'l_amt' => '', // Cost of item. - 'l_number' => '', // Item number. 127 char max. - 'l_qty' => '', // Item qty on order. Any positive integer. - 'l_taxamt' => '', // Item sales tax - 'l_itemweightvalue' => '', // The weight value of the item. - 'l_itemweightunit' => '', // The weight unit of the item. - 'l_itemheightvalue' => '', // The height value of the item. - 'l_itemheightunit' => '', // The height unit of the item. - 'l_itemwidthvalue' => '', // The width value of the item. - 'l_itemwidthunit' => '', // The width unit of the item. - 'l_itemlengthvalue' => '', // The length value of the item. - 'l_itemlengthunit' => '', // The length unit of the item. - 'l_ebayitemnumber' => '', // Auction item number. - 'l_ebayitemauctiontxnid' => '', // Auction transaction ID number. - 'l_ebayitemorderid' => '' // Auction order ID number. - ); +$Item = array( + 'l_name' => '', // Item name. 127 char max. + 'l_description' => '', + 'l_amt' => '', // Cost of item. + 'l_number' => '', // Item number. 127 char max. + 'l_qty' => '', // Item qty on order. Any positive integer. + 'l_taxamt' => '', // Item sales tax + 'l_itemweightvalue' => '', // The weight value of the item. + 'l_itemweightunit' => '', // The weight unit of the item. + 'l_itemheightvalue' => '', // The height value of the item. + 'l_itemheightunit' => '', // The height unit of the item. + 'l_itemwidthvalue' => '', // The width value of the item. + 'l_itemwidthunit' => '', // The width unit of the item. + 'l_itemlengthvalue' => '', // The length value of the item. + 'l_itemlengthunit' => '', // The length unit of the item. + 'l_ebayitemnumber' => '', // Auction item number. + 'l_ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'l_ebayitemorderid' => '' // Auction order ID number. +); array_push($OrderItems, $Item); $CCDetails = array( - 'creditcardtype' => '', // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. - 'acct' => '', // Required. Credit card number. No spaces or punctuation. - 'expdate' => '', // Required. Credit card expiration date. Format is MMYYYY - 'cvv2' => '', // Requirements determined by your PayPal account settings. Security digits for credit card. - 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY - 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. - ); + 'creditcardtype' => '', // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. + 'acct' => '', // Required. Credit card number. No spaces or punctuation. + 'expdate' => '', // Required. Credit card expiration date. Format is MMYYYY + 'cvv2' => '', // Requirements determined by your PayPal account settings. Security digits for credit card. + 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY + 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. +); $PayerInfo = array( - 'email' => '', // Email address of payer. - 'firstname' => '', // Unique PayPal customer ID for payer. - 'lastname' => '' // Status of payer. Values are verified or unverified - ); + 'email' => '', // Email address of payer. + 'firstname' => '', // Unique PayPal customer ID for payer. + 'lastname' => '' // Status of payer. Values are verified or unverified +); $BillingAddress = array( - 'street' => '', // Required. First street address. - 'street2' => '', // Second street address. - 'city' => '', // Required. Name of City. - 'state' => '', // Required. Name of State or Province. - 'countrycode' => '', // Required. Country code. - 'zip' => '', // Required. Postal code of payer. - 'phonenum' => '' // Phone Number of payer. 20 char max. - ); + 'street' => '', // Required. First street address. + 'street2' => '', // Second street address. + 'city' => '', // Required. Name of City. + 'state' => '', // Required. Name of State or Province. + 'countrycode' => '', // Required. Country code. + 'zip' => '', // Required. Postal code of payer. + 'phonenum' => '' // Phone Number of payer. 20 char max. +); $PayPalRequestData = array( - 'DRTFields' => $DRTFields, - 'PaymentDetails' => $PaymentDetails - ); + 'DRTFields' => $DRTFields, + 'PaymentDetails' => $PaymentDetails +); -$PayPalResult = $PayPal -> DoReferenceTransaction($PayPalRequestData); +$PayPalResult = $PayPal->DoReferenceTransaction($PayPalRequestData); echo '
';
 print_r($PayPalResult);
diff --git a/samples/rest/DoReferenceTransaction.php b/samples/rest/DoReferenceTransaction.php
new file mode 100644
index 00000000..da7b81bd
--- /dev/null
+++ b/samples/rest/DoReferenceTransaction.php
@@ -0,0 +1,26 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$orderId = isset($_GET['token']) ? $_GET['token'] : '';
+
+$PaymentResult = $PayPal->authorizeOrder($orderId);
+
+$authorizationId = isset($PaymentResult['authorization_id']) ? $PaymentResult['authorization_id'] : '';
+
+$PayPalResult = $PayPal->captureAutorizedOrder($authorizationId);
+
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/templates/classic/DoReferenceTransaction.php b/templates/classic/DoReferenceTransaction.php
index a496049a..59e465cb 100644
--- a/templates/classic/DoReferenceTransaction.php
+++ b/templates/classic/DoReferenceTransaction.php
@@ -5,119 +5,120 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $DRTFields = array(
-    'referenceid' => '', 						// Required.  A transaction ID from a previous purchase, such as a credit card charage using DoDirectPayment, or a billing agreement ID
-    'paymentaction' => '', 						// How you want to obtain payment.  Values are:  Authorization, Sale
-    'paymenttype' => '', 						// Specifies type of PayPal payment you require for the billing agreement.  Values are:  Any, InstantOnly
-    'ipaddress' => '', 							// IP address of the buyer's browser
-    'reqconfirmshipping' => '', 					// Whether you require that the buyer's shipping address on file with PayPal be a confirmed address or not.  Values are 0/1
-    'returnfmfdetails' => '', 					// Flag to indicate whether you want the results returned by Fraud Management Filters.  Values are 0/1
-    'softdescriptor' => '',                     // Information that is usually displayed in the account holder's statement.  23 char max.
-    'softdescriptorcity' => '',                 // A unique phone number, email address or URL, which is displayed on the account holder's statement.
-    'msgsubid' => ''								// A message ID used for idempotence to uniquely identify a message.
+    'referenceid' => '', 		// Required.  A transaction ID from a previous purchase, such as a credit card charage using DoDirectPayment, or a billing agreement ID
+    'paymentaction' => '', 		// How you want to obtain payment.  Values are:  Authorization, Sale
+    'paymenttype' => '', 		// Specifies type of PayPal payment you require for the billing agreement.  Values are:  Any, InstantOnly
+    'ipaddress' => '', 			// IP address of the buyer's browser
+    'reqconfirmshipping' => '', 	// Whether you require that the buyer's shipping address on file with PayPal be a confirmed address or not.  Values are 0/1
+    'returnfmfdetails' => '', 		// Flag to indicate whether you want the results returned by Fraud Management Filters.  Values are 0/1
+    'softdescriptor' => '',             // Information that is usually displayed in the account holder's statement.  23 char max.
+    'softdescriptorcity' => '',         // A unique phone number, email address or URL, which is displayed on the account holder's statement.
+    'msgsubid' => ''			// A message ID used for idempotence to uniquely identify a message.
 );
 
 $ShippingAddress = array(
-						'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-						'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-						'shiptostreet2' => '', 					// Second street address.  100 char max.
-						'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-						'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-						'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-						'shiptocountry' => '', 					// Required if shipping is included.  Country code of shipping address.  2 char max.
-						'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-						);
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
 
 $PaymentDetails = array(
-						'amt' => '', 							// Required. Total amount of the order, including shipping, handling, and tax.
-						'currencycode' => '', 					// A three-character currency code.  Default is USD.
-						'itemamt' => '', 						// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
-						'shippingamt' => '', 					// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
-						'insuranceamt' => '', 
-						'shippingdiscount' => '', 
-						'handlingamt' => '', 					// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
-						'taxamt' => '', 						// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
-						'insuranceoptionoffered' => '', 		// If true, the insurance drop-down on the PayPal review page displays Yes and shows the amount.
-						'desc' => '', 							// Description of items on the order.  127 char max.
-						'custom' => '', 						// Free-form field for your own use.  256 char max.
-						'invnum' => '', 						// Your own invoice or tracking number.  127 char max.
-						'notifyurl' => '', 						// URL for receiving Instant Payment Notifications
-						'recurring' => ''						// Flag to indicate a recurring transaction.  Values are:  Y for recurring.  Anything other than Y is not recurring.
-						);
+	'amt' => '', 				// Required. Total amount of the order, including shipping, handling, and tax.
+	'currencycode' => '', 			// A three-character currency code.  Default is USD.
+	'itemamt' => '', 			// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
+	'shippingamt' => '', 			// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+	'insuranceamt' => '', 
+	'shippingdiscount' => '', 
+	'handlingamt' => '', 			// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+	'taxamt' => '', 			// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
+	'insuranceoptionoffered' => '', 	// If true, the insurance drop-down on the PayPal review page displays Yes and shows the amount.
+	'desc' => '', 				// Description of items on the order.  127 char max.
+	'custom' => '', 			// Free-form field for your own use.  256 char max.
+	'invnum' => '', 			// Your own invoice or tracking number.  127 char max.
+	'notifyurl' => '', 			// URL for receiving Instant Payment Notifications
+	'recurring' => ''			// Flag to indicate a recurring transaction.  Values are:  Y for recurring.  Anything other than Y is not recurring.
+);
 
 // For order items you populate a nested array with multiple $Item arrays.  Normally you'll be looping through cart items to populate the $Item 
 // array and then push it into the $OrderItems array at the end of each loop for an entire collection of all items in $OrderItems.
 
 $OrderItems = array();
 $Item = array(
-			'l_itemcategory' => '', 					// One of the following values:  Digital, Physical
-			'l_name' => '', 							// Item name. 127 char max.
-			'l_description' => '', 						// Item description.  127 char max.
-			'l_amt' => '', 								// Cost of item.
-			'l_number' => '', 							// Item number.  127 char max.
-			'l_qty' => '', 								// Item qty on order.  Any positive integer.
-			'l_taxamt' => '', 							// Item sales tax
-			'l_itemweightvalue' => '', 					// The weight value of the item.
-			'l_itemweightunit' => '', 					// The weight unit of the item.
-			'l_itemheightvalue' => '', 					// The height value of the item.
-			'l_itemheightunit' => '', 					// The height unit of the item.
-			'l_itemwidthvalue' => '', 					// The width value of the item.
-			'l_itemwidthunit' => '', 					// The width unit of the item.
-			'l_itemlengthvalue' => '', 					// The length value of the item.
-			'l_itemlengthunit' => '',  					// The length unit of the item.
-			'l_ebayitemnumber' => '', 					// Auction item number.  
-			'l_ebayitemauctiontxnid' => '', 			// Auction transaction ID number.  
-			'l_ebayitemorderid' => '' 					// Auction order ID number.
-			);
+	'l_itemcategory' => '', 		// One of the following values:  Digital, Physical
+	'l_name' => '', 			// Item name. 127 char max.
+	'l_description' => '', 			// Item description.  127 char max.
+	'l_amt' => '', 				// Cost of item.
+	'l_number' => '', 			// Item number.  127 char max.
+	'l_qty' => '', 				// Item qty on order.  Any positive integer.
+	'l_taxamt' => '', 			// Item sales tax
+	'l_itemweightvalue' => '', 		// The weight value of the item.
+	'l_itemweightunit' => '', 		// The weight unit of the item.
+	'l_itemheightvalue' => '', 		// The height value of the item.
+	'l_itemheightunit' => '', 		// The height unit of the item.
+	'l_itemwidthvalue' => '', 		// The width value of the item.
+	'l_itemwidthunit' => '', 		// The width unit of the item.
+	'l_itemlengthvalue' => '', 		// The length value of the item.
+	'l_itemlengthunit' => '',  		// The length unit of the item.
+	'l_ebayitemnumber' => '', 		// Auction item number.  
+	'l_ebayitemauctiontxnid' => '', 	// Auction transaction ID number.  
+	'l_ebayitemorderid' => '' 		// Auction order ID number.
+);
 					
 array_push($OrderItems, $Item);
 
 $CCDetails = array(
-					'creditcardtype' => '', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-					'acct' => '', 								// Required.  Credit card number.  No spaces or punctuation.  
-					'expdate' => '', 							// Required.  Credit card expiration date.  Format is MMYYYY
-					'cvv2' => '', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-					'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-					'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-				);
+	'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 
 $PayerInfo = array(
-					'email' => '', 								// Email address of payer.
-					'firstname' => '', 							// Unique PayPal customer ID for payer.
-					'lastname' => ''						// Status of payer.  Values are verified or unverified
-				);
+	'email' => '', 			// Email address of payer.
+	'firstname' => '', 		// Unique PayPal customer ID for payer.
+	'lastname' => ''		// Status of payer.  Values are verified or unverified
+);
 				
 $BillingAddress = array(
-						'street' => '', 						// Required.  First street address.
-						'street2' => '', 						// Second street address.
-						'city' => '', 							// Required.  Name of City.
-						'state' => '', 							// Required. Name of State or Province.
-						'countrycode' => '', 					// Required.  Country code.
-						'zip' => '', 							// Required.  Postal code of payer.
-						'phonenum' => '' 						// Phone Number of payer.  20 char max.
-					);
+	'street' => '', 		// Required.  First street address.
+	'street2' => '', 		// Second street address.
+	'city' => '', 			// Required.  Name of City.
+	'state' => '', 			// Required. Name of State or Province.
+	'countrycode' => '', 		// Required.  Country code.
+	'zip' => '', 			// Required.  Postal code of payer.
+	'phonenum' => '' 		// Phone Number of payer.  20 char max.
+);
 					
 $PayPalRequestData = array(
-						'DRTFields' => $DRTFields, 
-						'ShippingAddress' => $ShippingAddress, 
-						'PaymentDetails' => $PaymentDetails, 
-						'OrderItems' => $OrderItems, 
-						'CCDetails' => $CCDetails, 
-						'PayerInfo' => $PayerInfo, 
-						'BillingAddress' => $BillingAddress
-						);
+	'DRTFields' => $DRTFields, 
+	'ShippingAddress' => $ShippingAddress, 
+	'PaymentDetails' => $PaymentDetails, 
+	'OrderItems' => $OrderItems, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo, 
+	'BillingAddress' => $BillingAddress
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->DoReferenceTransaction($PayPalRequestData);
diff --git a/templates/rest/DoReferenceTransaction.php b/templates/rest/DoReferenceTransaction.php
new file mode 100644
index 00000000..da7b81bd
--- /dev/null
+++ b/templates/rest/DoReferenceTransaction.php
@@ -0,0 +1,26 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$orderId = isset($_GET['token']) ? $_GET['token'] : '';
+
+$PaymentResult = $PayPal->authorizeOrder($orderId);
+
+$authorizationId = isset($PaymentResult['authorization_id']) ? $PaymentResult['authorization_id'] : '';
+
+$PayPalResult = $PayPal->captureAutorizedOrder($authorizationId);
+
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file

From b07132eede4aa6b8d253a6f32e69bc5e19169ce4 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 3 Nov 2025 18:49:21 +0530
Subject: [PATCH 021/146] CreateRecurringPaymentsProfile,
 GetRecurringPaymentsProfileDetails, ManageRecurringPaymentsProfileStatus
 Methods Completed

---
 .../CreateRecurringPaymentsProfile.php        | 155 +++++++--------
 .../GetRecurringPaymentsProfileDetails.php    |  23 +--
 .../ManageRecurringPaymentsProfileStatus.php  |  27 +--
 .../rest/CreateRecurringPaymentsProfile.php   | 108 +++++++++++
 .../GetRecurringPaymentsProfileDetails.php    |  31 +++
 .../ManageRecurringPaymentsProfileStatus.php  |  31 +++
 src/angelleye/PayPal/PayPalREST.php           | 144 ++++++++++++++
 .../CreateRecurringPaymentsProfile.php        | 181 +++++++++---------
 .../GetRecurringPaymentsProfileDetails.php    |  23 +--
 .../ManageRecurringPaymentsProfileStatus.php  |  27 +--
 .../rest/CreateRecurringPaymentsProfile.php   | 108 +++++++++++
 .../GetRecurringPaymentsProfileDetails.php    |  31 +++
 .../ManageRecurringPaymentsProfileStatus.php  |  31 +++
 13 files changed, 705 insertions(+), 215 deletions(-)
 create mode 100644 samples/rest/CreateRecurringPaymentsProfile.php
 create mode 100644 samples/rest/GetRecurringPaymentsProfileDetails.php
 create mode 100644 samples/rest/ManageRecurringPaymentsProfileStatus.php
 create mode 100644 templates/rest/CreateRecurringPaymentsProfile.php
 create mode 100644 templates/rest/GetRecurringPaymentsProfileDetails.php
 create mode 100644 templates/rest/ManageRecurringPaymentsProfileStatus.php

diff --git a/samples/classic/CreateRecurringPaymentsProfile.php b/samples/classic/CreateRecurringPaymentsProfile.php
index 7847e8b2..c0634412 100644
--- a/samples/classic/CreateRecurringPaymentsProfile.php
+++ b/samples/classic/CreateRecurringPaymentsProfile.php
@@ -3,20 +3,21 @@
 require_once('../../autoload.php');
 
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $CRPPFields = array(
-			'token' => '', 								// Token returned from PayPal SetExpressCheckout.  Can also use token returned from SetCustomerBillingAgreement.
-				);
+	'token' => 'EC-2A900424LS312982Y', 		// Token returned from PayPal SetExpressCheckout.  Can also use token returned from SetCustomerBillingAgreement.
+);
 				
 $DaysTimestamp = strtotime('now');
 $Mo = date('m', $DaysTimestamp);
@@ -25,90 +26,90 @@
 $StartDateGMT = $Year . '-' . $Mo . '-' . $Day . 'T00:00:00\Z';
 				
 $ProfileDetails = array(
-					'subscribername' => 'Tester Testerson', 					// Full name of the person receiving the product or service paid for by the recurring payment.  32 char max.
-					'profilestartdate' => $StartDateGMT, 					// Required.  The date when the billing for this profile begins.  Must be a valid date in UTC/GMT format.
-					'profilereference' => '' 					// The merchant's own unique invoice number or reference ID.  127 char max.
-				);
+	'subscribername' => 'Tester Testerson', 					// Full name of the person receiving the product or service paid for by the recurring payment.  32 char max.
+	'profilestartdate' => $StartDateGMT, 					// Required.  The date when the billing for this profile begins.  Must be a valid date in UTC/GMT format.
+	'profilereference' => '' 					// The merchant's own unique invoice number or reference ID.  127 char max.
+);
 				
 $ScheduleDetails = array(
-					'desc' => 'Angell EYE Web Hosting', 								// Required.  Description of the recurring payment.  This field must match the corresponding billing agreement description included in SetExpressCheckout.
-					'maxfailedpayments' => '', 					// The number of scheduled payment periods that can fail before the profile is automatically suspended.  
-					'autobillamt' => '1' 						// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.  Values can be: NoAutoBill or AddToNextBilling
-				);
+	'desc' => 'Angell EYE Web Hosting', 		// Required.  Description of the recurring payment.  This field must match the corresponding billing agreement description included in SetExpressCheckout.
+	'maxfailedpayments' => '', 			// The number of scheduled payment periods that can fail before the profile is automatically suspended.  
+	'autobillamt' => '1' 				// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.  Values can be: NoAutoBill or AddToNextBilling
+);
 				
 $BillingPeriod = array(
-					'trialbillingperiod' => '', 
-					'trialbillingfrequency' => '', 
-					'trialtotalbillingcycles' => '', 
-					'trialamt' => '', 
-					'billingperiod' => 'Day', 						// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
-					'billingfrequency' => '1', 					// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
-					'totalbillingcycles' => '0', 				// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
-					'amt' => '10.00', 								// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
-					'currencycode' => 'USD', 						// Required.  Three-letter currency code.
-					'shippingamt' => '', 						// Shipping amount for each billing cycle during the payment period.
-					'taxamt' => '' 								// Tax amount for each billing cycle during the payment period.
-				);
+	'trialbillingperiod' => '', 
+	'trialbillingfrequency' => '', 
+	'trialtotalbillingcycles' => '', 
+	'trialamt' => '', 
+	'billingperiod' => 'Day', 		// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+	'billingfrequency' => '1', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+	'totalbillingcycles' => '0', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+	'amt' => '10.00', 			// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+	'currencycode' => 'USD', 		// Required.  Three-letter currency code.
+	'shippingamt' => '', 			// Shipping amount for each billing cycle during the payment period.
+	'taxamt' => '' 				// Tax amount for each billing cycle during the payment period.
+);
 				
 $ActivationDetails = array(
-					'initamt' => '', 							// Initial non-recurring payment amount due immediatly upon profile creation.  Use an initial amount for enrolment or set-up fees.
-					'failedinitamtaction' => '', 				// By default, PayPal will suspend the pending profile in the event that the initial payment fails.  You can override this.  Values are: ContinueOnFailure or CancelOnFailure
-				);
+	'initamt' => '', 			// Initial non-recurring payment amount due immediatly upon profile creation.  Use an initial amount for enrolment or set-up fees.
+	'failedinitamtaction' => '', 		// By default, PayPal will suspend the pending profile in the event that the initial payment fails.  You can override this.  Values are: ContinueOnFailure or CancelOnFailure
+);
 				
 $CCDetails = array(
-					'creditcardtype' => 'Visa', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-					'acct' => '4635800000971893', 								// Required.  Credit card number.  No spaces or punctuation.  
-					'expdate' => '022019', 							// Required.  Credit card expiration date.  Format is MMYYYY
-					'cvv2' => '123', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-					'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-					'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-				);
+	'creditcardtype' => 'Visa', 		// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '4635800000971893', 		// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '022019', 			// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '123', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 			// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''			// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 				
 $PayerInfo = array(
-					'email' => 'tester@hey.com', 								// Email address of payer.
-					'payerid' => '', 							// Unique PayPal customer ID for payer.
-					'payerstatus' => '', 						// Status of payer.  Values are verified or unverified
-					'countrycode' => '', 						// Payer's country of residence in the form of the two letter code.
-					'business' => 'Testers, LLC' 							// Payer's business name.
-				);
+	'email' => 'tester@hey.com', 		// Email address of payer.
+	'payerid' => '', 			// Unique PayPal customer ID for payer.
+	'payerstatus' => '', 			// Status of payer.  Values are verified or unverified
+	'countrycode' => '', 			// Payer's country of residence in the form of the two letter code.
+	'business' => 'Testers, LLC' 		// Payer's business name.
+);
 				
 $PayerName = array(
-					'salutation' => '', 						// Payer's salutation.  20 char max.
-					'firstname' => 'Tester', 							// Payer's first name.  25 char max.
-					'middlename' => '', 						// Payer's middle name.  25 char max.
-					'lastname' => 'Testerson', 							// Payer's last name.  25 char max.
-					'suffix' => ''								// Payer's suffix.  12 char max.
-				);
+	'salutation' => '', 			// Payer's salutation.  20 char max.
+	'firstname' => 'Tester', 		// Payer's first name.  25 char max.
+	'middlename' => '', 			// Payer's middle name.  25 char max.
+	'lastname' => 'Testerson', 		// Payer's last name.  25 char max.
+	'suffix' => ''				// Payer's suffix.  12 char max.
+);
 				
 $BillingAddress = array(
-						'street' => '123 Test Ave.', 						// Required.  First street address.
-						'street2' => '', 						// Second street address.
-						'city' => 'Grandview', 							// Required.  Name of City.
-						'state' => 'MO', 							// Required. Name of State or Province.
-						'countrycode' => 'US', 					// Required.  Country code.
-						'zip' => '64030', 							// Required.  Postal code of payer.
-						'phonenum' => '' 						// Phone Number of payer.  20 char max.
-					);
+	'street' => '123 Test Ave.', 		// Required.  First street address.
+	'street2' => '', 			// Second street address.
+	'city' => 'Grandview', 			// Required.  Name of City.
+	'state' => 'MO', 			// Required. Name of State or Province.
+	'countrycode' => 'US', 			// Required.  Country code.
+	'zip' => '64030', 			// Required.  Postal code of payer.
+	'phonenum' => '' 			// Phone Number of payer.  20 char max.
+);
 					
 $ShippingAddress = array(
-						'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-						'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-						'shiptostreet2' => '', 					// Second street address.  100 char max.
-						'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-						'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-						'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-						'shiptocountrycode' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
-						'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-						);
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountrycode' => '', 	// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
 						
 $PayPalRequestData = array(
-'ProfileDetails' => $ProfileDetails, 
-'ScheduleDetails' => $ScheduleDetails, 
-'BillingPeriod' => $BillingPeriod, 
-'CCDetails' => $CCDetails, 
-'PayerInfo' => $PayerInfo, 
-'PayerName' => $PayerName, 
-'BillingAddress' => $BillingAddress
+	'ProfileDetails' => $ProfileDetails, 
+	'ScheduleDetails' => $ScheduleDetails, 
+	'BillingPeriod' => $BillingPeriod, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo, 
+	'PayerName' => $PayerName, 
+	'BillingAddress' => $BillingAddress
 );
 
 $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($PayPalRequestData);
diff --git a/samples/classic/GetRecurringPaymentsProfileDetails.php b/samples/classic/GetRecurringPaymentsProfileDetails.php
index 3c09e90b..d4dbe718 100644
--- a/samples/classic/GetRecurringPaymentsProfileDetails.php
+++ b/samples/classic/GetRecurringPaymentsProfileDetails.php
@@ -5,21 +5,22 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $GRPPDFields = array(
-				   'profileid' => 'I-YMGN1WN4YY9E'			// Profile ID of the profile you want to get details for.
-				   );
+	'profileid' => 'I-YMGN1WN4YY9E'			// Profile ID of the profile you want to get details for.
+);
 				   
 $PayPalRequestData = array('GRPPDFields'=>$GRPPDFields);
 
diff --git a/samples/classic/ManageRecurringPaymentsProfileStatus.php b/samples/classic/ManageRecurringPaymentsProfileStatus.php
index d902e52e..94d07adc 100644
--- a/samples/classic/ManageRecurringPaymentsProfileStatus.php
+++ b/samples/classic/ManageRecurringPaymentsProfileStatus.php
@@ -5,23 +5,24 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MRPPSFields = array(
-					'profileid' => 'I-LH2MJXG27TR6', 				// Required. Recurring payments profile ID returned from CreateRecurring...
-					'action' => 'Reactivate', 				// Required. The action to be performed.  Mest be: Cancel, Suspend, Reactivate
-					'note' => ''					// The reason for the change in status.  For express checkout the message will be included in email to buyers.  Can also be seen in both accounts in the status history.
-					);
+	'profileid' => 'I-LH2MJXG27TR6', 		// Required. Recurring payments profile ID returned from CreateRecurring...
+	'action' => 'Reactivate', 			// Required. The action to be performed.  Mest be: Cancel, Suspend, Reactivate
+	'note' => ''					// The reason for the change in status.  For express checkout the message will be included in email to buyers.  Can also be seen in both accounts in the status history.
+);
 					
 $PayPalRequestData = array('MRPPSFields'=>$MRPPSFields);
 
diff --git a/samples/rest/CreateRecurringPaymentsProfile.php b/samples/rest/CreateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..cc6a009a
--- /dev/null
+++ b/samples/rest/CreateRecurringPaymentsProfile.php
@@ -0,0 +1,108 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$ProductData = array(
+        "name" => "Angell EYE Web Hosting",
+        "description" => "Web hosting recurring subscription",
+        "type" => "SERVICE",
+        "category" => "SOFTWARE",
+);
+
+$PlanData = array(
+        "product_id" => '',
+        "name" => "Daily Hosting Plan",
+        "description" => "Daily recurring billing for hosting",
+        "billing_cycles" => array(
+                array(
+                        "frequency" => array(
+                                "interval_unit" => "DAY",
+                                "interval_count" => 1
+                        ),
+                        "tenure_type" => "REGULAR",
+                        "sequence" => 1,
+                        "total_cycles" => 0, // 0 = infinite
+                        "pricing_scheme" => array(
+                                "fixed_price" => array(
+                                "value" => "10.00",
+                                "currency_code" => "USD"
+                                )
+                        )
+                )
+        ),
+        "payment_preferences" => array(
+                "auto_bill_outstanding" => true,
+                "setup_fee_failure_action" => "CONTINUE",
+                "payment_failure_threshold" => 3
+        )
+);
+
+$SubscriptionData = array(
+        "plan_id" => '',
+        "start_time" => gmdate("Y-m-d\TH:i:s\Z", strtotime("+10 minutes")),
+        "subscriber" => array(
+                "name" => array(
+                        "given_name" => "Tester",
+                        "surname" => "Testerson"
+                ),
+                "email_address" => "tester@hey.com",
+                "shipping_address" => array(
+                        "name" => array("full_name" => "Tester Testerson"),
+                        "address" => array(
+                                "address_line_1" => "123 Test Ave.",
+                                "admin_area_2" => "Grandview",
+                                "admin_area_1" => "MO",
+                                "postal_code" => "64030",
+                                "country_code" => "US"
+                        )
+                )
+        ),
+        "application_context" => array(
+                "brand_name" => "Angell EYE Web Hosting",
+                "locale" => "en-US",
+                "shipping_preference" => "SET_PROVIDED_ADDRESS",
+                "user_action" => "SUBSCRIBE_NOW",
+                'return_url' => $domain . 'samples/rest/GetRecurringPaymentsProfileDetails.php',
+		'cancel_url' => $domain . 'samples/rest/', 
+        )
+);
+
+$PayPalRequestData = array(
+	'ProductData' => $ProductData, 
+	'PlanData' => $PlanData, 
+	'SubscriptionData' => $SubscriptionData, 
+);
+
+$PayPalResult = $PayPal->CreateSubscriptionProfile($PayPalRequestData);
+
+if ($PayPalResult['success']) {
+        $approve_url = '';
+        if (!empty($PayPalResult['response']['links'])) {
+                foreach ($PayPalResult['response']['links'] as $link) {
+                        if (isset($link['rel']) && $link['rel'] === 'approve') {
+                                $approve_url = $link['href'];
+                                break;
+                        }
+                }
+        }
+	echo 'Click here to continue.

'; + + echo '
';
+	print_r($PayPalResult);
+} else {
+    	echo 'Error creating order: ' . $PayPalResult['error'];
+}
\ No newline at end of file
diff --git a/samples/rest/GetRecurringPaymentsProfileDetails.php b/samples/rest/GetRecurringPaymentsProfileDetails.php
new file mode 100644
index 00000000..8a9adb59
--- /dev/null
+++ b/samples/rest/GetRecurringPaymentsProfileDetails.php
@@ -0,0 +1,31 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+	'token' => isset($_GET['token']) ? $_GET['token'] : '',
+        'ba_token' => isset($_GET['ba_token']) ? $_GET['ba_token'] : '',
+        'subscription_id' => isset($_GET['subscription_id']) ? $_GET['subscription_id'] : '',
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetSubscriptionProfile($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/ManageRecurringPaymentsProfileStatus.php b/samples/rest/ManageRecurringPaymentsProfileStatus.php
new file mode 100644
index 00000000..d72c79c1
--- /dev/null
+++ b/samples/rest/ManageRecurringPaymentsProfileStatus.php
@@ -0,0 +1,31 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+        'subscription_id' => 'I-1443MGDVTCP8',                                  // Subscription ID of the profile you want to manage
+        'subscription_action' => 'cancel',                                      // options: cancel | suspend | activate
+        'subscription_reason' => 'Canceling the subscription profile.'          // Reason for the change in status
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->ManageSubscriptionProfile($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index e4198478..abe1def3 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -624,6 +624,150 @@ public function DoDirectPayment($paymentData) {
         return $responseSimplified;
     }
 
+    /**
+     * Create a recurring payments profile using PayPal REST APIs.
+     *
+     * This method automates the process of creating a PayPal product, 
+     * billing plan, and subscription (recurring profile) in sequence.
+     *
+     * Steps:
+     * 1. Create a product using the `/v1/catalogs/products` endpoint.
+     * 2. Create a billing plan linked to the product using `/v1/billing/plans`.
+     * 3. Create a subscription (recurring payments profile) using `/v1/billing/subscriptions`.
+     */
+    public function CreateSubscriptionProfile($DataArray) {
+        // Extract the data arrays or initialize as empty arrays
+        $ProductData = isset($DataArray['ProductData']) ? $DataArray['ProductData'] : array();
+        $PlanData = isset($DataArray['PlanData']) ? $DataArray['PlanData'] : array();
+        $SubscriptionData = isset($DataArray['SubscriptionData']) ? $DataArray['SubscriptionData'] : array();
+
+        // Step 1: Create the product in PayPal Catalog
+        $productResponse = $this->makeRequest('/v1/catalogs/products', 'POST', $ProductData);
+
+        $responseSimplified = array();
+
+        // Check if product creation succeeded (status 2xx)
+        if ($productResponse['status_code'] >= 200 && $productResponse['status_code'] < 300) {
+            // Attach created product_id to the plan data
+            $PlanData['product_id'] = isset($productResponse['body']['id']) ? $productResponse['body']['id'] : '';
+
+            // Step 2: Create a billing plan associated with the product
+            $planResponse = $this->makeRequest('/v1/billing/plans', 'POST', $PlanData);
+
+            if ($planResponse['status_code'] >= 200 && $planResponse['status_code'] < 300) {
+                // Attach the created plan_id to the subscription data
+                $SubscriptionData['plan_id'] = isset($planResponse['body']['id']) ? $planResponse['body']['id'] : '';
+
+                // Step 3: Create a subscription (recurring payments profile)
+                $subscriptionResponse = $this->makeRequest('/v1/billing/subscriptions', 'POST', $SubscriptionData);
+
+                if ($subscriptionResponse['status_code'] >= 200 && $subscriptionResponse['status_code'] < 300) {
+                    $responseSimplified = array(
+                        'success' => true,
+                        'subscription_id' => !empty($subscriptionResponse['body']['id']) ? $subscriptionResponse['body']['id'] : '',
+                        'status' => !empty($subscriptionResponse['status_code']) ? $subscriptionResponse['status_code'] : 0,
+                        'response' => !empty($subscriptionResponse['body']) ? $subscriptionResponse['body'] : [],
+                        'raw_response' => !empty($subscriptionResponse['raw_response']) ? $subscriptionResponse['raw_response'] : [],
+                    );
+                } else {
+                    $responseSimplified = array(
+                        'success' => false,
+                        'status' => $subscriptionResponse['status_code'],
+                        'error' => !empty($subscriptionResponse['body']) ? $subscriptionResponse['body'] : [],
+                        'raw_response' => !empty($subscriptionResponse['raw_response']) ? $subscriptionResponse['raw_response'] : [],
+                    );
+                }
+            } else {
+                $responseSimplified = array(
+                    'success' => false,
+                    'status' => $planResponse['status_code'],
+                    'error' => !empty($planResponse['body']) ? $planResponse['body'] : [],
+                    'raw_response' => !empty($planResponse['raw_response']) ? $planResponse['raw_response'] : [],
+                );
+            }
+        } else {
+            $responseSimplified = array(
+                'success' => false,
+                'status' => $productResponse['status_code'],
+                'error' => !empty($productResponse['body']) ? $productResponse['body'] : [],
+                'raw_response' => !empty($productResponse['raw_response']) ? $productResponse['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
+    /**
+     * Retrieves details of a PayPal subscription profile using the REST API.
+     *
+     * This method sends a GET request to the PayPal `/v1/billing/subscriptions/{subscription_id}` 
+     * endpoint to fetch information about a specific subscription, including its status and 
+     * associated details.
+     */
+    public function GetSubscriptionProfile($DataArray) {
+        try {
+            $subscriptionId = isset($DataArray['subscription_id']) ? $DataArray['subscription_id'] : '';
+
+            $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId, 'GET');
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['status_code'],
+                'full_response' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Manage a PayPal subscription profile by performing actions such as cancel, suspend, or activate.
+     *
+     * This function interacts with the PayPal REST API to manage an existing subscription.
+     * Supported actions typically include `cancel`, `suspend`, or `activate`.
+     */
+    public function ManageSubscriptionProfile($DataArray) {
+        try {
+            $subscriptionId = isset($DataArray['subscription_id']) ? $DataArray['subscription_id'] : '';
+            $subscriptionAction = isset($DataArray['subscription_action']) ? strtolower($DataArray['subscription_action']) : '';
+            $subscriptionReason = isset($DataArray['subscription_reason']) ? array('reason' => $DataArray['subscription_reason']) : array();
+
+            $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId . '/' . $subscriptionAction, 'POST', $subscriptionReason);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'],
+                    'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['status_code'],
+                'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/CreateRecurringPaymentsProfile.php b/templates/classic/CreateRecurringPaymentsProfile.php
index 76218312..1fef4e3d 100644
--- a/templates/classic/CreateRecurringPaymentsProfile.php
+++ b/templates/classic/CreateRecurringPaymentsProfile.php
@@ -5,128 +5,129 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CRPPFields = array(
-    'token' => '', 								// Token returned from PayPal SetExpressCheckout.  Can also use token returned from SetCustomerBillingAgreement.
-    'softdescriptor' => '',                     // Information that is usually displayed in the account holder's statement.  23 char max.
-    'softdescriptorcity' => '',                 // A unique phone number, emaili address or URL, which is displayed on the account holder's statement.
+    'token' => '', 			// Token returned from PayPal SetExpressCheckout.  Can also use token returned from SetCustomerBillingAgreement.
+    'softdescriptor' => '',             // Information that is usually displayed in the account holder's statement.  23 char max.
+    'softdescriptorcity' => '',         // A unique phone number, emaili address or URL, which is displayed on the account holder's statement.
 );
 				
 $ProfileDetails = array(
-					'subscribername' => '', 					// Full name of the person receiving the product or service paid for by the recurring payment.  32 char max.
-					'profilestartdate' => '', 					// Required.  The date when the billing for this profile begins.  Must be a valid date in UTC/GMT format.
-					'profilereference' => '' 					// The merchant's own unique invoice number or reference ID.  127 char max.
-				);
+	'subscribername' => '', 	// Full name of the person receiving the product or service paid for by the recurring payment.  32 char max.
+	'profilestartdate' => '', 	// Required.  The date when the billing for this profile begins.  Must be a valid date in UTC/GMT format.
+	'profilereference' => '' 	// The merchant's own unique invoice number or reference ID.  127 char max.
+);
 				
 $ScheduleDetails = array(
-					'desc' => '', 								// Required.  Description of the recurring payment.  This field must match the corresponding billing agreement description included in SetExpressCheckout.
-					'maxfailedpayments' => '', 					// The number of scheduled payment periods that can fail before the profile is automatically suspended.  
-					'autobilloutamt' => '' 						// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.  Values can be: NoAutoBill or AddToNextBilling
-				);
+	'desc' => '', 			// Required.  Description of the recurring payment.  This field must match the corresponding billing agreement description included in SetExpressCheckout.
+	'maxfailedpayments' => '', 	// The number of scheduled payment periods that can fail before the profile is automatically suspended.  
+	'autobilloutamt' => '' 		// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.  Values can be: NoAutoBill or AddToNextBilling
+);
 				
 $BillingPeriod = array(
-					'trialbillingperiod' => '', 
-					'trialbillingfrequency' => '', 
-					'trialtotalbillingcycles' => '', 
-					'trialamt' => '', 
-					'billingperiod' => '', 						// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
-					'billingfrequency' => '', 					// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
-					'totalbillingcycles' => '', 				// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
-					'amt' => '', 								// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
-					'currencycode' => '', 						// Required.  Three-letter currency code.
-					'shippingamt' => '', 						// Shipping amount for each billing cycle during the payment period.
-					'taxamt' => '' 								// Tax amount for each billing cycle during the payment period.
-				);
+	'trialbillingperiod' => '', 
+	'trialbillingfrequency' => '', 
+	'trialtotalbillingcycles' => '', 
+	'trialamt' => '', 
+	'billingperiod' => '', 			// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+	'billingfrequency' => '', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+	'totalbillingcycles' => '', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+	'amt' => '', 				// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+	'currencycode' => '', 			// Required.  Three-letter currency code.
+	'shippingamt' => '', 			// Shipping amount for each billing cycle during the payment period.
+	'taxamt' => '' 				// Tax amount for each billing cycle during the payment period.
+);
 				
 $ActivationDetails = array(
-					'initamt' => '', 							// Initial non-recurring payment amount due immediatly upon profile creation.  Use an initial amount for enrolment or set-up fees.
-					'failedinitamtaction' => '', 				// By default, PayPal will suspend the pending profile in the event that the initial payment fails.  You can override this.  Values are: ContinueOnFailure or CancelOnFailure
-				);
+	'initamt' => '', 			// Initial non-recurring payment amount due immediatly upon profile creation.  Use an initial amount for enrolment or set-up fees.
+	'failedinitamtaction' => '', 		// By default, PayPal will suspend the pending profile in the event that the initial payment fails.  You can override this.  Values are: ContinueOnFailure or CancelOnFailure
+);
 				
 $CCDetails = array(
-					'creditcardtype' => '', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-					'acct' => '', 								// Required.  Credit card number.  No spaces or punctuation.  
-					'expdate' => '', 							// Required.  Credit card expiration date.  Format is MMYYYY
-					'cvv2' => '', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-					'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-					'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-				);
+	'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 				
 $PayerInfo = array(
-					'email' => '', 								// Email address of payer.
-					'payerid' => '', 							// Unique PayPal customer ID for payer.
-					'payerstatus' => '', 						// Status of payer.  Values are verified or unverified
-					'business' => '' 							// Payer's business name.
-				);
+	'email' => '', 		// Email address of payer.
+	'payerid' => '', 	// Unique PayPal customer ID for payer.
+	'payerstatus' => '', 	// Status of payer.  Values are verified or unverified
+	'business' => '' 	// Payer's business name.
+);
 				
 $PayerName = array(
-					'salutation' => '', 						// Payer's salutation.  20 char max.
-					'firstname' => '', 							// Payer's first name.  25 char max.
-					'middlename' => '', 						// Payer's middle name.  25 char max.
-					'lastname' => '', 							// Payer's last name.  25 char max.
-					'suffix' => ''								// Payer's suffix.  12 char max.
-				);
+	'salutation' => '', 	// Payer's salutation.  20 char max.
+	'firstname' => '', 	// Payer's first name.  25 char max.
+	'middlename' => '', 	// Payer's middle name.  25 char max.
+	'lastname' => '', 	// Payer's last name.  25 char max.
+	'suffix' => ''		// Payer's suffix.  12 char max.
+);
 				
 $BillingAddress = array(
-						'street' => '', 						// Required.  First street address.
-						'street2' => '', 						// Second street address.
-						'city' => '', 							// Required.  Name of City.
-						'state' => '', 							// Required. Name of State or Province.
-						'countrycode' => '', 					// Required.  Country code.
-						'zip' => '', 							// Required.  Postal code of payer.
-						'phonenum' => '' 						// Phone Number of payer.  20 char max.
-					);
+	'street' => '', 	// Required.  First street address.
+	'street2' => '', 	// Second street address.
+	'city' => '', 		// Required.  Name of City.
+	'state' => '', 		// Required. Name of State or Province.
+	'countrycode' => '', 	// Required.  Country code.
+	'zip' => '', 		// Required.  Postal code of payer.
+	'phonenum' => '' 	// Phone Number of payer.  20 char max.
+);
 					
 $ShippingAddress = array(
-						'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-						'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-						'shiptostreet2' => '', 					// Second street address.  100 char max.
-						'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-						'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-						'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-						'shiptocountry' => '', 					// Required if shipping is included.  Country code of shipping address.  2 char max.
-						'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-						);
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
 						
 // For order items you populate a nested array with multiple $Item arrays.  Normally you'll be looping through cart items to populate the $Item 
 // array and then push it into the $OrderItems array at the end of each loop for an entire collection of all items in $OrderItems.
 
 $OrderItems = array();		
 $Item	 = array(
-						'l_itemcategory' => '', 				// One of the following values:  Digital, Physical
-						'l_name' => '', 						// Item Name.  127 char max.
-						'l_desc' => '', 						// Item description.  127 char max.
-						'l_amt' => '', 							// Cost of individual item.
-						'l_number' => '', 						// Item Number.  127 char max.
-						'l_qty' => '', 							// Item quantity.  Must be any positive integer.  
-						'l_taxamt' => '' 						// Item's sales tax amount.
-				);
+	'l_itemcategory' => '', 	// One of the following values:  Digital, Physical
+	'l_name' => '', 		// Item Name.  127 char max.
+	'l_desc' => '', 		// Item description.  127 char max.
+	'l_amt' => '', 			// Cost of individual item.
+	'l_number' => '', 		// Item Number.  127 char max.
+	'l_qty' => '', 			// Item quantity.  Must be any positive integer.  
+	'l_taxamt' => '' 		// Item's sales tax amount.
+);
 array_push($OrderItems, $Item);
 
 $PayPalRequestData = array(
-						'CRPPFields' => $CRPPFields, 
-						'ProfileDetails' => $ProfileDetails, 
-						'ScheduleDetails' => $ScheduleDetails, 
-						'BillingPeriod' => $BillingPeriod, 
-						'ActivationDetails' => $ActivationDetails, 
-						'CCDetails' => $CCDetails, 
-						'PayerInfo' => $PayerInfo, 
-						'PayerName' => $PayerName, 
-						'BillingAddress' => $BillingAddress, 
-						'ShippingAddress' => $ShippingAddress, 
-						'OrderItems' => $OrderItems
-						);
+	'CRPPFields' => $CRPPFields, 
+	'ProfileDetails' => $ProfileDetails, 
+	'ScheduleDetails' => $ScheduleDetails, 
+	'BillingPeriod' => $BillingPeriod, 
+	'ActivationDetails' => $ActivationDetails, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo, 
+	'PayerName' => $PayerName, 
+	'BillingAddress' => $BillingAddress, 
+	'ShippingAddress' => $ShippingAddress, 
+	'OrderItems' => $OrderItems
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($PayPalRequestData);
diff --git a/templates/classic/GetRecurringPaymentsProfileDetails.php b/templates/classic/GetRecurringPaymentsProfileDetails.php
index f4b27f54..6461350f 100644
--- a/templates/classic/GetRecurringPaymentsProfileDetails.php
+++ b/templates/classic/GetRecurringPaymentsProfileDetails.php
@@ -5,21 +5,22 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $GRPPDFields = array(
-				   'profileid' => ''			// Profile ID of the profile you want to get details for.
-				   );
+	'profileid' => ''			// Profile ID of the profile you want to get details for.
+);
 				   
 $PayPalRequestData = array('GRPPDFields'=>$GRPPDFields);
 
diff --git a/templates/classic/ManageRecurringPaymentsProfileStatus.php b/templates/classic/ManageRecurringPaymentsProfileStatus.php
index 965224ab..fab38d9a 100644
--- a/templates/classic/ManageRecurringPaymentsProfileStatus.php
+++ b/templates/classic/ManageRecurringPaymentsProfileStatus.php
@@ -5,23 +5,24 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MRPPSFields = array(
-					'profileid' => '', 				// Required. Recurring payments profile ID returned from CreateRecurring...
-					'action' => '', 				// Required. The action to be performed.  Mest be: Cancel, Suspend, Reactivate
-					'note' => ''					// The reason for the change in status.  For express checkout the message will be included in email to buyers.  Can also be seen in both accounts in the status history.
-					);
+	'profileid' => '', 	// Required. Recurring payments profile ID returned from CreateRecurring...
+	'action' => '', 	// Required. The action to be performed.  Mest be: Cancel, Suspend, Reactivate
+	'note' => ''		// The reason for the change in status.  For express checkout the message will be included in email to buyers.  Can also be seen in both accounts in the status history.
+);
 					
 $PayPalRequestData = array('MRPPSFields'=>$MRPPSFields);
 
diff --git a/templates/rest/CreateRecurringPaymentsProfile.php b/templates/rest/CreateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..2d32ffee
--- /dev/null
+++ b/templates/rest/CreateRecurringPaymentsProfile.php
@@ -0,0 +1,108 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$ProductData = array(
+        "name" => "",
+        "description" => "",
+        "type" => "",
+        "category" => "",
+);
+
+$PlanData = array(
+        "product_id" => "",
+        "name" => "",
+        "description" => "",
+        "billing_cycles" => array(
+                array(
+                        "frequency" => array(
+                                "interval_unit" => "",
+                                "interval_count" => ""
+                        ),
+                        "tenure_type" => "",
+                        "sequence" => "",
+                        "total_cycles" => "", // 0 = infinite
+                        "pricing_scheme" => array(
+                                "fixed_price" => array(
+                                        "value" => "",
+                                        "currency_code" => ""
+                                )
+                        )
+                )
+        ),
+        "payment_preferences" => array(
+                "auto_bill_outstanding" => "",
+                "setup_fee_failure_action" => "",
+                "payment_failure_threshold" => ""
+        )
+);
+
+$SubscriptionData = array(
+        "plan_id" => "",
+        "start_time" => "",
+        "subscriber" => array(
+                "name" => array(
+                        "given_name" => "",
+                        "surname" => ""
+                ),
+                "email_address" => "",
+                "shipping_address" => array(
+                        "name" => array("full_name" => ""),
+                        "address" => array(
+                                "address_line_1" => "",
+                                "admin_area_2" => "",
+                                "admin_area_1" => "",
+                                "postal_code" => "",
+                                "country_code" => ""
+                        )
+                )
+        ),
+        "application_context" => array(
+                "brand_name" => "",
+                "locale" => "",
+                "shipping_preference" => "",
+                "user_action" => "",
+                'return_url' => "",
+		'cancel_url' => "", 
+        )
+);
+
+$PayPalRequestData = array(
+	'ProductData' => $ProductData, 
+	'PlanData' => $PlanData, 
+	'SubscriptionData' => $SubscriptionData, 
+);
+
+$PayPalResult = $PayPal->CreateSubscriptionProfile($PayPalRequestData);
+
+if ($PayPalResult['success']) {
+        $approve_url = '';
+        if (!empty($PayPalResult['response']['links'])) {
+                foreach ($PayPalResult['response']['links'] as $link) {
+                        if (isset($link['rel']) && $link['rel'] === 'approve') {
+                                $approve_url = $link['href'];
+                                break;
+                        }
+                }
+        }
+	echo 'Click here to continue.

'; + + echo '
';
+	print_r($PayPalResult);
+} else {
+    	echo 'Error creating order: ' . $PayPalResult['error'];
+}
\ No newline at end of file
diff --git a/templates/rest/GetRecurringPaymentsProfileDetails.php b/templates/rest/GetRecurringPaymentsProfileDetails.php
new file mode 100644
index 00000000..088b8943
--- /dev/null
+++ b/templates/rest/GetRecurringPaymentsProfileDetails.php
@@ -0,0 +1,31 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+	'token' => '',
+        'ba_token' => '',
+        'subscription_id' => '',
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetSubscriptionProfile($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/ManageRecurringPaymentsProfileStatus.php b/templates/rest/ManageRecurringPaymentsProfileStatus.php
new file mode 100644
index 00000000..0a7c2107
--- /dev/null
+++ b/templates/rest/ManageRecurringPaymentsProfileStatus.php
@@ -0,0 +1,31 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+        'subscription_id' => '',             	// Subscription ID of the profile you want to manage
+        'subscription_action' => '',        	// options: cancel | suspend | activate
+        'subscription_reason' => ''          	// Reason for the change in status
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->ManageSubscriptionProfile($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 015911c2bd34c0e04e74222d222d675c5a409719 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Tue, 4 Nov 2025 18:01:35 +0530
Subject: [PATCH 022/146] Completed UpdateRecurringPaymentProfile,
 GetPalDetails and MassPay Methods in REST

---
 samples/classic/GetPalDetails.php             |  19 +--
 samples/classic/MassPay.php                   |  65 +++++----
 .../UpdateRecurringPaymentsProfile.php        | 137 +++++++++---------
 .../rest/CreateRecurringPaymentsProfile.php   |   4 +-
 samples/rest/GetPalDetails.php                |  24 +++
 samples/rest/MassPay.php                      |  71 +++++++++
 .../rest/UpdateRecurringPaymentsProfile.php   |  41 ++++++
 src/angelleye/PayPal/PayPalREST.php           | 126 ++++++++++++++--
 templates/classic/GetPalDetails.php           |  19 +--
 templates/classic/MassPay.php                 |  65 +++++----
 .../UpdateRecurringPaymentsProfile.php        | 137 +++++++++---------
 templates/rest/GetPalDetails.php              |  24 +++
 templates/rest/MassPay.php                    |  71 +++++++++
 .../rest/UpdateRecurringPaymentsProfile.php   |  41 ++++++
 14 files changed, 609 insertions(+), 235 deletions(-)
 create mode 100644 samples/rest/GetPalDetails.php
 create mode 100644 samples/rest/MassPay.php
 create mode 100644 samples/rest/UpdateRecurringPaymentsProfile.php
 create mode 100644 templates/rest/GetPalDetails.php
 create mode 100644 templates/rest/MassPay.php
 create mode 100644 templates/rest/UpdateRecurringPaymentsProfile.php

diff --git a/samples/classic/GetPalDetails.php b/samples/classic/GetPalDetails.php
index 0a0e1823..bf2141ec 100644
--- a/samples/classic/GetPalDetails.php
+++ b/samples/classic/GetPalDetails.php
@@ -5,16 +5,17 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->GetPalDetails();
diff --git a/samples/classic/MassPay.php b/samples/classic/MassPay.php
index 14e0bdbf..963dd286 100644
--- a/samples/classic/MassPay.php
+++ b/samples/classic/MassPay.php
@@ -5,50 +5,51 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
-
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MPFields = array(
-					'emailsubject' => 'Test MassPay', 						// The subject line of the email that PayPal sends when the transaction is completed.  Same for all recipients.  255 char max.
-					'currencycode' => 'USD', 						// Three-letter currency code.
-					'receivertype' => 'EmailAddress' 						// Indicates how you identify the recipients of payments in this call to MassPay.  Must be EmailAddress or UserID
-				);
+	'emailsubject' => 'Test MassPay', 	// The subject line of the email that PayPal sends when the transaction is completed.  Same for all recipients.  255 char max.
+	'currencycode' => 'USD', 		// Three-letter currency code.
+	'receivertype' => 'EmailAddress' 	// Indicates how you identify the recipients of payments in this call to MassPay.  Must be EmailAddress or UserID
+);
 
 // Typically, you'll loop through some sort of records to build your MPItems array. 
 // Here I simply include 3 items individually.  
 
 $Item1 = array(
-					'l_email' => 'andrew_1342623385_per@angelleye.com', 							// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
-					'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
-					'l_amt' => '10.00', 								// Required.  Payment amount.
-					'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
-					'l_note' => '' 								// Custom note for each recipient.
-			);
+	'l_email' => 'andrew_1342623385_per@angelleye.com', 		// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
+	'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
+	'l_amt' => '10.00', 						// Required.  Payment amount.
+	'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
+	'l_note' => '' 							// Custom note for each recipient.
+);
 			
 $Item2 = array(
-					'l_email' => 'usb_1329725429_biz@angelleye.com', 							// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
-					'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
-					'l_amt' => '10.00', 								// Required.  Payment amount.
-					'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
-					'l_note' => '' 								// Custom note for each recipient.
-			);
+	'l_email' => 'usb_1329725429_biz@angelleye.com', 		// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
+	'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
+	'l_amt' => '10.00', 						// Required.  Payment amount.
+	'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
+	'l_note' => '' 							// Custom note for each recipient.
+);
 			
 $Item3 = array(
-					'l_email' => 'andrew_1277258815_per@angelleye.com', 							// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
-					'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
-					'l_amt' => '10.00', 								// Required.  Payment amount.
-					'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
-					'l_note' => '' 								// Custom note for each recipient.
-			);
+	'l_email' => 'andrew_1277258815_per@angelleye.com', 		// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
+	'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
+	'l_amt' => '10.00', 						// Required.  Payment amount.
+	'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
+	'l_note' => '' 							// Custom note for each recipient.
+);
 									
 $MPItems = array($Item1, $Item2, $Item3);  // etc
 
diff --git a/samples/classic/UpdateRecurringPaymentsProfile.php b/samples/classic/UpdateRecurringPaymentsProfile.php
index 58411782..b3351b44 100644
--- a/samples/classic/UpdateRecurringPaymentsProfile.php
+++ b/samples/classic/UpdateRecurringPaymentsProfile.php
@@ -5,90 +5,91 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $URPPFields = array(
-				   'profileid' => 'I-54Y4CNH8T196', 							// Required.  Recurring payments ID.
-				   'note' => '', 								// Note about the reason for the update to the profile.  Included in EC profile notification emails and in details pages.
-				   'desc' => '', 								// Description of the recurring payment profile.
-				   'subscribername' => '', 						// Full name of the person receiving the product or service paid for by the recurring payment profile.
-				   'profilereference' => '', 					// The merchant's own unique reference or invoice number.
-				   'additionalbillingcycles' => '', 			// The number of additional billing cycles to add to this profile.
-				   'amt' => '1.2', 								// Billing amount for each cycle in the subscription, not including shipping and tax.  Express Checkout profiles can only be updated by 20% every 180 days.
-				   'shippingamt' => '', 						// Shipping amount for each billing cycle during the payment period.
-				   'taxamt' => '', 								// Tax amount for each billing cycle during the payment period.
-				   'outstandingamt' => '', 						// The current past-due or outstanding amount.  You can only decrease this amount.  
-				   'autobilloutamt' => '', 						// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.
-				   'maxfailedpayments' => '', 					// The number of failed payments allowed before the profile is automatically suspended.  The specified value cannot be less than the current number of failed payments for the profile.
-				   'profilestartdate' => ''						// The date when the billing for this profile begins.  UTC/GMT format.
-				   );
+	'profileid' => 'I-54Y4CNH8T196', 		// Required.  Recurring payments ID.
+	'note' => '', 					// Note about the reason for the update to the profile.  Included in EC profile notification emails and in details pages.
+	'desc' => '', 					// Description of the recurring payment profile.
+	'subscribername' => '', 			// Full name of the person receiving the product or service paid for by the recurring payment profile.
+	'profilereference' => '', 			// The merchant's own unique reference or invoice number.
+	'additionalbillingcycles' => '', 		// The number of additional billing cycles to add to this profile.
+	'amt' => '1.2', 				// Billing amount for each cycle in the subscription, not including shipping and tax.  Express Checkout profiles can only be updated by 20% every 180 days.
+	'shippingamt' => '', 				// Shipping amount for each billing cycle during the payment period.
+	'taxamt' => '', 				// Tax amount for each billing cycle during the payment period.
+	'outstandingamt' => '', 			// The current past-due or outstanding amount.  You can only decrease this amount.  
+	'autobilloutamt' => '', 			// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.
+	'maxfailedpayments' => '', 			// The number of failed payments allowed before the profile is automatically suspended.  The specified value cannot be less than the current number of failed payments for the profile.
+	'profilestartdate' => ''			// The date when the billing for this profile begins.  UTC/GMT format.
+);
 
 $BillingAddress = array(
-					'street' => '', 						// Required.  First street address.
-					'street2' => '', 						// Second street address.
-					'city' => '', 							// Required.  Name of City.
-					'state' => '', 							// Required. Name of State or Province.
-					'countrycode' => '', 					// Required.  Country code.
-					'zip' => '', 							// Required.  Postal code of payer.
-					'phonenum' => '' 						// Phone Number of payer.  20 char max.
-				);
+	'street' => '', 		// Required.  First street address.
+	'street2' => '', 		// Second street address.
+	'city' => '', 			// Required.  Name of City.
+	'state' => '', 			// Required. Name of State or Province.
+	'countrycode' => '', 		// Required.  Country code.
+	'zip' => '', 			// Required.  Postal code of payer.
+	'phonenum' => '' 		// Phone Number of payer.  20 char max.
+);
 
 $ShippingAddress = array(
-					'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-					'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-					'shiptostreet2' => '', 					// Second street address.  100 char max.
-					'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-					'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-					'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-					'shiptocountry' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
-					'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-					);
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
 
 $BillingPeriod = array(
-				'trialbillingperiod' => '', 
-				'trialbillingfrequency' => '', 
-				'trialtotalbillingcycles' => '', 
-				'trialamt' => '', 
-				'billingperiod' => '', 						// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
-				'billingfrequency' => '', 					// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
-				'totalbillingcycles' => '', 				// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
-				'amt' => '', 								// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
-				'currencycode' => '', 						// Required.  Three-letter currency code.
-			);
+	'trialbillingperiod' => '', 
+	'trialbillingfrequency' => '', 
+	'trialtotalbillingcycles' => '', 
+	'trialamt' => '', 
+	'billingperiod' => '', 			// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+	'billingfrequency' => '', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+	'totalbillingcycles' => '', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+	'amt' => '', 				// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+	'currencycode' => '', 			// Required.  Three-letter currency code.
+);
 
 $CCDetails = array(
-				'creditcardtype' => '', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-				'acct' => '', 								// Required.  Credit card number.  No spaces or punctuation.  
-				'expdate' => '', 							// Required.  Credit card expiration date.  Format is MMYYYY
-				'cvv2' => '', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-				'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-				'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-			);
+	'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 
 $PayerInfo = array(
-				'email' => '', 								// Payer's email address.
-				'firstname' => '', 							// Required.  Payer's first name.
-				'lastname' => ''							// Required.  Payer's last name.
-			);
+	'email' => '', 			// Payer's email address.
+	'firstname' => '', 		// Required.  Payer's first name.
+	'lastname' => ''		// Required.  Payer's last name.
+);
 			
 $PayPalRequestData = array(
-						'URPPFields' => $URPPFields, 
-						'BillingAddress' => $BillingAddress, 
-						'ShippingAddress' => $ShippingAddress, 
-						'BillingPeriod' => $BillingPeriod, 
-						'CCDetails' => $CCDetails, 
-						'PayerInfo' => $PayerInfo
-						);
+	'URPPFields' => $URPPFields, 
+	'BillingAddress' => $BillingAddress, 
+	'ShippingAddress' => $ShippingAddress, 
+	'BillingPeriod' => $BillingPeriod, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->UpdateRecurringPaymentsProfile($PayPalRequestData);
diff --git a/samples/rest/CreateRecurringPaymentsProfile.php b/samples/rest/CreateRecurringPaymentsProfile.php
index cc6a009a..4bdd2710 100644
--- a/samples/rest/CreateRecurringPaymentsProfile.php
+++ b/samples/rest/CreateRecurringPaymentsProfile.php
@@ -38,8 +38,8 @@
                         "total_cycles" => 0, // 0 = infinite
                         "pricing_scheme" => array(
                                 "fixed_price" => array(
-                                "value" => "10.00",
-                                "currency_code" => "USD"
+                                        "value" => "10.00",
+                                        "currency_code" => "USD"
                                 )
                         )
                 )
diff --git a/samples/rest/GetPalDetails.php b/samples/rest/GetPalDetails.php
new file mode 100644
index 00000000..0f06924d
--- /dev/null
+++ b/samples/rest/GetPalDetails.php
@@ -0,0 +1,24 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetPalDetails();
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/samples/rest/MassPay.php b/samples/rest/MassPay.php
new file mode 100644
index 00000000..37783d52
--- /dev/null
+++ b/samples/rest/MassPay.php
@@ -0,0 +1,71 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$SenderBatchHeaders = array(
+	'sender_batch_id' => uniqid("batch_"),                          // A unique identifier of the batch payout. Must be unique for each payout.
+	"email_subject"   => "Test MassPay via PayPal REST API",        // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients.  255 char max.
+        "email_message"   => "You have received a payout!",             // The message that PayPal sends to the recipients of the payout email. 255 char max.
+);
+
+// Typically, you'll loop through some sort of records to build your MPItems array. 
+// Here I simply include 3 items individually.  
+
+$Item1 = array(
+	"recipient_type" => "EMAIL",                            // The type of recipient. Must be EMAIL or PHONE.
+        "amount" => array(
+                "value" => "0.01",                              // The amount to be paid to the recipient.
+                "currency" => "USD"                             // The currency code.
+        ),
+        "receiver" => "andrew_1342623385_per@angelleye.com",    // The recipient's email address.
+        "note" => "Thanks for your work!",                      // A note to the recipient.
+        "sender_item_id" => "item_1"                            // A unique identifier for the item in the payout batch.
+);
+			
+$Item2 = array(
+	"recipient_type" => "EMAIL",                            // The type of recipient. Must be EMAIL or PHONE.
+        "amount" => array(
+                "value" => "0.01",                              // The amount to be paid to the recipient.
+                "currency" => "USD"                             // The currency code.
+        ),
+        "receiver" => "usb_1329725429_biz@angelleye.com",       // The recipient's email address.
+        "note" => "Payment for services",                       // A note to the recipient.
+        "sender_item_id" => "item_2"                            // A unique identifier for the item in the payout batch.
+);
+			
+$Item3 = array(
+	"recipient_type" => "EMAIL",                            // The type of recipient. Must be EMAIL or PHONE.
+        "amount" => array(
+                "value" => "0.01",                              // The amount to be paid to the recipient.
+                "currency" => "USD"                             // The currency code.
+        ),
+        "receiver" => "andrew_1277258815_per@angelleye.com",    // The recipient's email address.
+        "note" => "Thank you!",                                 // A note to the recipient.
+        "sender_item_id" => "item_3"                            // A unique identifier for the item in the payout batch.
+);
+									
+$Items = array($Item1, $Item2, $Item3);  // etc
+
+$PayPalRequestData = array('sender_batch_header'=>$SenderBatchHeaders, 'items' => $Items);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->MassPay($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/UpdateRecurringPaymentsProfile.php b/samples/rest/UpdateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..3b309e2b
--- /dev/null
+++ b/samples/rest/UpdateRecurringPaymentsProfile.php
@@ -0,0 +1,41 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$ReplaceFields = array(
+	"op" => "replace",
+        "path" => "/shipping_amount",
+        "value" => [
+                "currency_code" => "USD",
+                "value" => "1.00"
+        ]
+);
+
+$Patches = array($ReplaceFields);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+        'subscription_id' => 'I-W67GUR0BDTG6',
+        'patches' => $Patches,
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->UpdateSubscriptionProfile($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index abe1def3..7baf75a8 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -384,7 +384,7 @@ public function createOrder($orderData)
                 return [
                     'success' => true,
                     'order_id' => $response['body']['id'],
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'approval_url' => $this->getApprovalUrl($response['body']['links']),
                     'full_response' => $response['body']
                 ];
@@ -393,7 +393,7 @@ public function createOrder($orderData)
             return [
                 'success' => false,
                 'error' => 'Failed to create order',
-                'status_code' => $response['status_code'],
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
                 'details' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -422,7 +422,7 @@ public function getOrder($orderId)
             return [
                 'success' => false,
                 'error' => 'Failed to get order details',
-                'status_code' => $response['status_code'],
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
                 'details' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -445,7 +445,7 @@ public function authorizeOrder($orderId)
                 return [
                     'success' => true,
                     'authorization_id' => $response['body']['purchase_units'][0]['payments']['authorizations'][0]['id'],
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'full_response' => $response['body']
                 ];
             }
@@ -453,7 +453,7 @@ public function authorizeOrder($orderId)
             return [
                 'success' => false,
                 'error' => 'Failed to authorize order',
-                'status_code' => $response['status_code'],
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
                 'details' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -476,7 +476,7 @@ public function captureOrder($orderId)
                 return [
                     'success' => true,
                     'capture_id' => $response['body']['purchase_units'][0]['payments']['captures'][0]['id'],
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'full_response' => $response['body']
                 ];
             }
@@ -484,7 +484,7 @@ public function captureOrder($orderId)
             return [
                 'success' => false,
                 'error' => 'Failed to capture order',
-                'status_code' => $response['status_code'],
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
                 'details' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -507,7 +507,7 @@ public function captureAutorizedOrder($authorizationId)
                 return [
                     'success' => true,
                     'capture_id' => $response['body']['id'],
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'full_response' => $response['body']
                 ];
             }
@@ -515,7 +515,7 @@ public function captureAutorizedOrder($authorizationId)
             return [
                 'success' => false,
                 'error' => 'Failed to capture order',
-                'status_code' => $response['status_code'],
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
                 'details' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -537,7 +537,7 @@ public function getCapturedOrderDetails($captureId)
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'full_response' => $response['body']
                 ];
             }
@@ -545,7 +545,7 @@ public function getCapturedOrderDetails($captureId)
             return [
                 'success' => false,
                 'error' => '',
-                'status' => $response['status_code'],
+                'status' => $response['body']['status'] ?? $response['status_code'],
                 'full_response' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -713,7 +713,7 @@ public function GetSubscriptionProfile($DataArray) {
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'full_response' => $response['body']
                 ];
             }
@@ -721,7 +721,7 @@ public function GetSubscriptionProfile($DataArray) {
             return [
                 'success' => false,
                 'error' => '',
-                'status' => $response['status_code'],
+                'status' => $response['body']['status'] ?? $response['status_code'],
                 'full_response' => $response['body']
             ];
         } catch (\Exception $e) {
@@ -749,7 +749,7 @@ public function ManageSubscriptionProfile($DataArray) {
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
-                    'status' => $response['body']['status'],
+                    'status' => $response['body']['status'] ?? $response['status_code'],
                     'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
                 ];
             }
@@ -757,7 +757,7 @@ public function ManageSubscriptionProfile($DataArray) {
             return [
                 'success' => false,
                 'error' => '',
-                'status' => $response['status_code'],
+                'status' => $response['body']['status'] ?? $response['status_code'],
                 'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
             ];
         } catch (\Exception $e) {
@@ -768,6 +768,102 @@ public function ManageSubscriptionProfile($DataArray) {
         }
     }
 
+    public function UpdateSubscriptionProfile($DataArray) {
+        try {
+            $subscriptionId = isset($DataArray['subscription_id']) ? $DataArray['subscription_id'] : '';
+            $patches = isset($DataArray['patches']) ? $DataArray['patches'] : array();
+
+            $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId, 'PATCH', $patches);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['body']['status'] ?? $response['status_code'],
+                'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Executes a PayPal Mass Payment (Payout) request using the REST API.
+     *
+     * This function sends a POST request to the PayPal Payouts endpoint (`/v1/payments/payouts`)
+     * with the provided payout data array. It returns the response status, success flag,
+     * and the full API response for further inspection.
+     */
+    public function MassPay($DataArray) {
+        try {
+            $response = $this->makeRequest('/v1/payments/payouts', 'POST', $DataArray);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['body']['status'] ?? $response['status_code'],
+                'full_response' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Retrieves PayPal account details of the authenticated user using the REST Identity API.
+     *
+     * This method calls the `/v1/identity/oauth2/userinfo?schema=paypalv1.1` endpoint
+     * to get information about the merchant’s PayPal account such as email, account ID,
+     * verification status, and country. It serves as the REST equivalent of the classic
+     * NVP `GetPalDetails` API.
+     */
+    public function GetPalDetails() {
+        try {
+            $response = $this->makeRequest('/v1/identity/oauth2/userinfo?schema=paypalv1.1');
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['body']['status'] ?? $response['status_code'],
+                'full_response' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/GetPalDetails.php b/templates/classic/GetPalDetails.php
index 184574c8..ca53efec 100644
--- a/templates/classic/GetPalDetails.php
+++ b/templates/classic/GetPalDetails.php
@@ -5,16 +5,17 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->GetPalDetails();
diff --git a/templates/classic/MassPay.php b/templates/classic/MassPay.php
index 2dd35d15..59eeadbe 100644
--- a/templates/classic/MassPay.php
+++ b/templates/classic/MassPay.php
@@ -5,50 +5,51 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
-
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MPFields = array(
-					'emailsubject' => '', 						// The subject line of the email that PayPal sends when the transaction is completed.  Same for all recipients.  255 char max.
-					'currencycode' => '', 						// Three-letter currency code.
-					'receivertype' => '' 						// Indicates how you identify the recipients of payments in this call to MassPay.  Must be EmailAddress or UserID
-				);
+	'emailsubject' => '', 		// The subject line of the email that PayPal sends when the transaction is completed.  Same for all recipients.  255 char max.
+	'currencycode' => '', 		// Three-letter currency code.
+	'receivertype' => '' 		// Indicates how you identify the recipients of payments in this call to MassPay.  Must be EmailAddress or UserID
+);
 
 // Typically, you'll loop through some sort of records to build your MPItems array. 
 // Here I simply include 3 items individually.  
 
 $Item1 = array(
-					'l_email' => '', 							// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
-					'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
-					'l_amt' => '', 								// Required.  Payment amount.
-					'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
-					'l_note' => '' 								// Custom note for each recipient.
-			);
+	'l_email' => '', 		// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
+	'l_receiverid' => '', 		// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
+	'l_amt' => '', 			// Required.  Payment amount.
+	'l_uniqueid' => '', 		// Transaction-specific ID number for tracking in an accounting system.
+	'l_note' => '' 			// Custom note for each recipient.
+);
 			
 $Item2 = array(
-					'l_email' => '', 							// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
-					'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
-					'l_amt' => '', 								// Required.  Payment amount.
-					'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
-					'l_note' => '' 								// Custom note for each recipient.
-			);
+	'l_email' => '', 		// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
+	'l_receiverid' => '', 		// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
+	'l_amt' => '', 			// Required.  Payment amount.
+	'l_uniqueid' => '', 		// Transaction-specific ID number for tracking in an accounting system.
+	'l_note' => '' 			// Custom note for each recipient.
+);
 			
 $Item3 = array(
-					'l_email' => '', 							// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
-					'l_receiverid' => '', 						// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
-					'l_amt' => '', 								// Required.  Payment amount.
-					'l_uniqueid' => '', 						// Transaction-specific ID number for tracking in an accounting system.
-					'l_note' => '' 								// Custom note for each recipient.
-			);
+	'l_email' => '', 		// Required.  Email address of recipient.  You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two.
+	'l_receiverid' => '', 		// Required.  ReceiverID of recipient.  Must specify this or email address, but not both.
+	'l_amt' => '', 			// Required.  Payment amount.
+	'l_uniqueid' => '', 		// Transaction-specific ID number for tracking in an accounting system.
+	'l_note' => '' 			// Custom note for each recipient.
+);
 									
 $MPItems = array($Item1, $Item2, $Item3);  // etc
 
diff --git a/templates/classic/UpdateRecurringPaymentsProfile.php b/templates/classic/UpdateRecurringPaymentsProfile.php
index 56f45ac0..d752af30 100644
--- a/templates/classic/UpdateRecurringPaymentsProfile.php
+++ b/templates/classic/UpdateRecurringPaymentsProfile.php
@@ -5,90 +5,91 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $URPPFields = array(
-				   'profileid' => '', 							// Required.  Recurring payments ID.
-				   'note' => '', 								// Note about the reason for the update to the profile.  Included in EC profile notification emails and in details pages.
-				   'desc' => '', 								// Description of the recurring payment profile.
-				   'subscribername' => '', 						// Full name of the person receiving the product or service paid for by the recurring payment profile.
-				   'profilereference' => '', 					// The merchant's own unique reference or invoice number.
-				   'additionalbillingcycles' => '', 			// The number of additional billing cycles to add to this profile.
-				   'amt' => '', 								// Billing amount for each cycle in the subscription, not including shipping and tax.  Express Checkout profiles can only be updated by 20% every 180 days.
-				   'shippingamt' => '', 						// Shipping amount for each billing cycle during the payment period.
-				   'taxamt' => '', 								// Tax amount for each billing cycle during the payment period.
-				   'outstandingamt' => '', 						// The current past-due or outstanding amount.  You can only decrease this amount.  
-				   'autobilloutamt' => '', 						// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.
-				   'maxfailedpayments' => '', 					// The number of failed payments allowed before the profile is automatically suspended.  The specified value cannot be less than the current number of failed payments for the profile.
-				   'profilestartdate' => ''						// The date when the billing for this profile begins.  UTC/GMT format.
-				   );
+	'profileid' => '', 			// Required.  Recurring payments ID.
+	'note' => '', 				// Note about the reason for the update to the profile.  Included in EC profile notification emails and in details pages.
+	'desc' => '', 				// Description of the recurring payment profile.
+	'subscribername' => '', 		// Full name of the person receiving the product or service paid for by the recurring payment profile.
+	'profilereference' => '', 		// The merchant's own unique reference or invoice number.
+	'additionalbillingcycles' => '', 	// The number of additional billing cycles to add to this profile.
+	'amt' => '', 				// Billing amount for each cycle in the subscription, not including shipping and tax.  Express Checkout profiles can only be updated by 20% every 180 days.
+	'shippingamt' => '', 			// Shipping amount for each billing cycle during the payment period.
+	'taxamt' => '', 			// Tax amount for each billing cycle during the payment period.
+	'outstandingamt' => '', 		// The current past-due or outstanding amount.  You can only decrease this amount.  
+	'autobilloutamt' => '', 		// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.
+	'maxfailedpayments' => '', 		// The number of failed payments allowed before the profile is automatically suspended.  The specified value cannot be less than the current number of failed payments for the profile.
+	'profilestartdate' => ''		// The date when the billing for this profile begins.  UTC/GMT format.
+);
 
 $BillingAddress = array(
-					'street' => '', 						// Required.  First street address.
-					'street2' => '', 						// Second street address.
-					'city' => '', 							// Required.  Name of City.
-					'state' => '', 							// Required. Name of State or Province.
-					'countrycode' => '', 					// Required.  Country code.
-					'zip' => '', 							// Required.  Postal code of payer.
-					'phonenum' => '' 						// Phone Number of payer.  20 char max.
-				);
+	'street' => '', 		// Required.  First street address.
+	'street2' => '', 		// Second street address.
+	'city' => '', 			// Required.  Name of City.
+	'state' => '', 			// Required. Name of State or Province.
+	'countrycode' => '', 		// Required.  Country code.
+	'zip' => '', 			// Required.  Postal code of payer.
+	'phonenum' => '' 		// Phone Number of payer.  20 char max.
+);
 
 $ShippingAddress = array(
-					'shiptoname' => '', 					// Required if shipping is included.  Person's name associated with this address.  32 char max.
-					'shiptostreet' => '', 					// Required if shipping is included.  First street address.  100 char max.
-					'shiptostreet2' => '', 					// Second street address.  100 char max.
-					'shiptocity' => '', 					// Required if shipping is included.  Name of city.  40 char max.
-					'shiptostate' => '', 					// Required if shipping is included.  Name of state or province.  40 char max.
-					'shiptozip' => '', 						// Required if shipping is included.  Postal code of shipping address.  20 char max.
-					'shiptocountry' => '', 				// Required if shipping is included.  Country code of shipping address.  2 char max.
-					'shiptophonenum' => ''					// Phone number for shipping address.  20 char max.
-					);
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
 
 $BillingPeriod = array(
-				'trialbillingperiod' => '', 
-				'trialbillingfrequency' => '', 
-				'trialtotalbillingcycles' => '', 
-				'trialamt' => '', 
-				'billingperiod' => '', 						// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
-				'billingfrequency' => '', 					// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
-				'totalbillingcycles' => '', 				// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
-				'amt' => '', 								// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
-				'currencycode' => '', 						// Required.  Three-letter currency code.
-			);
+	'trialbillingperiod' => '', 
+	'trialbillingfrequency' => '', 
+	'trialtotalbillingcycles' => '', 
+	'trialamt' => '', 
+	'billingperiod' => '', 			// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+	'billingfrequency' => '', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+	'totalbillingcycles' => '', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+	'amt' => '', 				// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+	'currencycode' => '', 			// Required.  Three-letter currency code.
+);
 
 $CCDetails = array(
-				'creditcardtype' => '', 					// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
-				'acct' => '', 								// Required.  Credit card number.  No spaces or punctuation.  
-				'expdate' => '', 							// Required.  Credit card expiration date.  Format is MMYYYY
-				'cvv2' => '', 								// Requirements determined by your PayPal account settings.  Security digits for credit card.
-				'startdate' => '', 							// Month and year that Maestro or Solo card was issued.  MMYYYY
-				'issuenumber' => ''							// Issue number of Maestro or Solo card.  Two numeric digits max.
-			);
+	'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
 
 $PayerInfo = array(
-				'email' => '', 								// Payer's email address.
-				'firstname' => '', 							// Required.  Payer's first name.
-				'lastname' => ''							// Required.  Payer's last name.
-			);
+	'email' => '', 			// Payer's email address.
+	'firstname' => '', 		// Required.  Payer's first name.
+	'lastname' => ''		// Required.  Payer's last name.
+);
 			
 $PayPalRequestData = array(
-						'URPPFields' => $URPPFields, 
-						'BillingAddress' => $BillingAddress, 
-						'ShippingAddress' => $ShippingAddress, 
-						'BillingPeriod' => $BillingPeriod, 
-						'CCDetails' => $CCDetails, 
-						'PayerInfo' => $PayerInfo
-						);
+	'URPPFields' => $URPPFields, 
+	'BillingAddress' => $BillingAddress, 
+	'ShippingAddress' => $ShippingAddress, 
+	'BillingPeriod' => $BillingPeriod, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->UpdateRecurringPaymentsProfile($PayPalRequestData);
diff --git a/templates/rest/GetPalDetails.php b/templates/rest/GetPalDetails.php
new file mode 100644
index 00000000..0f06924d
--- /dev/null
+++ b/templates/rest/GetPalDetails.php
@@ -0,0 +1,24 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetPalDetails();
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/templates/rest/MassPay.php b/templates/rest/MassPay.php
new file mode 100644
index 00000000..6870c0eb
--- /dev/null
+++ b/templates/rest/MassPay.php
@@ -0,0 +1,71 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$SenderBatchHeaders = array(
+	'sender_batch_id' => "",        // A unique identifier of the batch payout. Must be unique for each payout.
+	"email_subject"   => "",        // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients.  255 char max.
+        "email_message"   => "",        // The message that PayPal sends to the recipients of the payout email. 255 char max.
+);
+
+// Typically, you'll loop through some sort of records to build your MPItems array. 
+// Here I simply include 3 items individually.  
+
+$Item1 = array(
+	"recipient_type" => "",         // The type of recipient. Must be EMAIL or PHONE.
+        "amount" => array(
+                "value" => "",          // The amount to be paid to the recipient.
+                "currency" => ""        // The currency code.
+        ),
+        "receiver" => "",               // The recipient's email address.
+        "note" => "",                   // A note to the recipient.
+        "sender_item_id" => ""          // A unique identifier for the item in the payout batch.
+);
+			
+$Item2 = array(
+	"recipient_type" => "",         // The type of recipient. Must be EMAIL or PHONE.
+        "amount" => array(
+                "value" => "",          // The amount to be paid to the recipient.
+                "currency" => ""        // The currency code.
+        ),
+        "receiver" => "",               // The recipient's email address.
+        "note" => "",                   // A note to the recipient.
+        "sender_item_id" => ""          // A unique identifier for the item in the payout batch.
+);
+			
+$Item3 = array(
+	"recipient_type" => "",         // The type of recipient. Must be EMAIL or PHONE.
+        "amount" => array(
+                "value" => "",          // The amount to be paid to the recipient.
+                "currency" => ""        // The currency code.
+        ),
+        "receiver" => "",               // The recipient's email address.
+        "note" => "",                   // A note to the recipient.
+        "sender_item_id" => ""          // A unique identifier for the item in the payout batch.
+);
+									
+$Items = array($Item1, $Item2, $Item3);  // etc
+
+$PayPalRequestData = array('sender_batch_header'=>$SenderBatchHeaders, 'items' => $Items);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->MassPay($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/UpdateRecurringPaymentsProfile.php b/templates/rest/UpdateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..b62ffe03
--- /dev/null
+++ b/templates/rest/UpdateRecurringPaymentsProfile.php
@@ -0,0 +1,41 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$ReplaceFields = array(
+	"op" => "",
+        "path" => "",
+        "value" => [
+                "currency_code" => "",
+                "value" => ""
+        ]
+);
+
+$Patches = array($ReplaceFields);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+        'subscription_id' => '',
+        'patches' => $Patches,
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->UpdateSubscriptionProfile($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From f875bdcc3c927ea1f00f65407007719f1c2e4151 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 5 Nov 2025 18:07:30 +0530
Subject: [PATCH 023/146] Payment Options Method Completed

---
 samples/classic/GetPaymentOptions.php   | 33 +++++++++++++------------
 samples/rest/GetPaymentOptions.php      | 29 ++++++++++++++++++++++
 templates/classic/GetPaymentOptions.php | 33 +++++++++++++------------
 templates/rest/GetPaymentOptions.php    | 29 ++++++++++++++++++++++
 4 files changed, 92 insertions(+), 32 deletions(-)
 create mode 100644 samples/rest/GetPaymentOptions.php
 create mode 100644 templates/rest/GetPaymentOptions.php

diff --git a/samples/classic/GetPaymentOptions.php b/samples/classic/GetPaymentOptions.php
index ce7a9378..b772bb99 100644
--- a/samples/classic/GetPaymentOptions.php
+++ b/samples/classic/GetPaymentOptions.php
@@ -3,28 +3,29 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayKey = 'AP-8GH334440A259981L';
-$PayPalResult = $PayPal->GetPaymentOptions($PayKey);
+$PayPalResult = $PayPal->Adaptive->GetPaymentOptions($PayKey);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/GetPaymentOptions.php b/samples/rest/GetPaymentOptions.php
new file mode 100644
index 00000000..de3daf80
--- /dev/null
+++ b/samples/rest/GetPaymentOptions.php
@@ -0,0 +1,29 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayKey = '61H082912X9690433';
+$PayPalResult = $PayPal->getOrder($PayKey);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/classic/GetPaymentOptions.php b/templates/classic/GetPaymentOptions.php
index 210b0101..fe4bed13 100644
--- a/templates/classic/GetPaymentOptions.php
+++ b/templates/classic/GetPaymentOptions.php
@@ -3,28 +3,29 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayKey = '';
-$PayPalResult = $PayPal->GetPaymentOptions($PayKey);
+$PayPalResult = $PayPal->Adaptive->GetPaymentOptions($PayKey);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/GetPaymentOptions.php b/templates/rest/GetPaymentOptions.php
new file mode 100644
index 00000000..d1f49cd4
--- /dev/null
+++ b/templates/rest/GetPaymentOptions.php
@@ -0,0 +1,29 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayKey = '';
+$PayPalResult = $PayPal->getOrder($PayKey);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 931e93c0a6ce876e52509c1f9ec8b7972e1cd44c Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 10 Nov 2025 18:08:37 +0530
Subject: [PATCH 024/146] Add README File for the REST Sample Files

---
 samples/rest/README.md | 333 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 333 insertions(+)
 create mode 100644 samples/rest/README.md

diff --git a/samples/rest/README.md b/samples/rest/README.md
new file mode 100644
index 00000000..b7ef4b8a
--- /dev/null
+++ b/samples/rest/README.md
@@ -0,0 +1,333 @@
+# PayPal REST API PHP Samples
+
+This directory contains PHP sample scripts demonstrating how to use various PayPal API operations through the REST SDK.  
+Each method is a standalone example showing how to make authenticated requests, send payloads, and handle responses for different PayPal services such as payments, invoicing, recurring billing, and account management.
+
+**Note:**  
+All required arguments, headers, and payload data are defined and passed within each respective file.  
+You can inspect each file individually to view the parameters and payload structure used in that API call.
+
+---
+
+### **AddBankAccount.php**
+Demonstrates how to link a bank account to a PayPal account.
+
+---
+
+### **AddPaymentCard.php**
+Shows how to add a credit or debit card to a PayPal account.
+
+---
+
+### **BMButtonSearch.php**
+Retrieves a list of hosted PayPal buttons based on specific search criteria.
+
+---
+
+### **BMCreateButton.php**
+Creates a new PayPal payment button using the Button Manager API.
+
+---
+
+### **BMGetButtonDetails.php**
+Fetches detailed information for a specific hosted PayPal button.
+
+---
+
+### **BMGetInventory.php**
+Retrieves inventory details associated with a PayPal hosted button.
+
+---
+
+### **BMManageButtonStatus.php**
+Updates the status (e.g., activate or delete) of a PayPal hosted button.
+
+---
+
+### **BMSetInventory.php**
+Sets or updates inventory tracking for hosted button items.
+
+---
+
+### **BMUpdateButton.php**
+Updates configuration or parameters of an existing hosted button.
+
+---
+
+### **CancelInvoice.php**
+Cancels an existing PayPal invoice that has not been paid.
+
+---
+
+### **ConvertCurrency.php**
+Converts an amount between two currencies using PayPal’s exchange rate.
+
+---
+
+### **CreateAccount.php**
+Creates a new PayPal personal or business account via the API.
+
+---
+
+### **CreateAndSendInvoice.php**
+Creates an invoice and sends it immediately to the customer.
+
+---
+
+### **CreateInvoice.php**
+Creates a draft invoice that can be sent later.
+
+---
+
+### **CreateRecurringPaymentsProfile.php**
+Creates a recurring billing profile for automatic payments.
+
+---
+
+### **DeleteInvoice.php**
+Deletes a draft invoice from the merchant’s account.
+
+---
+
+### **DoDirectPayment.php**
+Performs a direct payment using credit card details (no PayPal redirection).
+
+---
+
+### **DoExpressCheckoutPayment.php**
+Completes the Express Checkout process after buyer approval.
+
+---
+
+### **DoExpressCheckoutPayment-Callback.php**
+Handles callback responses after an Express Checkout payment is completed.
+
+---
+
+### **DoExpressCheckoutPayment-RedeemedOffers.php**
+Processes Express Checkout payments that include redeemed offers.
+
+---
+
+### **DoReferenceTransaction.php**
+Performs a payment using a stored billing agreement or reference transaction ID.
+
+---
+
+### **ExecutePayment.php**
+Executes an approved PayPal payment after user authorization.
+
+---
+
+### **FinancingBannerEnrollment.php**
+Handles merchant enrollment for PayPal’s financing banner program.
+
+---
+
+### **GetAccessToken.php**
+Retrieves an OAuth 2.0 access token for authenticating API calls.
+
+---
+
+### **GetAdvancedPersonalData.php**
+Retrieves advanced account or personal data for an authenticated user.
+
+---
+
+### **GetBalance.php**
+Fetches the current account balance across all available currencies.
+
+---
+
+### **GetBasicPersonalData.php**
+Retrieves basic PayPal account information for an authenticated user.
+
+---
+
+### **GetInvoiceDetails.php**
+Retrieves details and line items for a specific invoice.
+
+---
+
+### **GetPalDetails.php**
+Fetches account details related to a PayPal merchant or business.
+
+---
+
+### **GetPaymentOptions.php**
+Retrieves available payment options for a given transaction or checkout.
+
+---
+
+### **GetRecurringPaymentsProfileDetails.php**
+Retrieves information about an existing recurring payment profile.
+
+---
+
+### **GetShippingAddresses.php**
+Retrieves saved shipping addresses associated with a PayPal buyer.
+
+---
+
+### **GetTransactionDetails.php**
+Retrieves full details for a specific PayPal transaction.
+
+---
+
+### **GetVerifiedStatus.php**
+Checks whether a PayPal account is verified or unverified.
+
+---
+
+### **ManageRecurringPaymentsProfileStatus.php**
+Suspends, cancels, or reactivates a recurring payment profile.
+
+---
+
+### **MarkInvoiceAsPaid.php**
+Marks an invoice as paid (for manual/offline payments).
+
+---
+
+### **MarkInvoiceAsRefunded.php**
+Marks an invoice as refunded.
+
+---
+
+### **MarkInvoiceAsUnpaid.php**
+Marks a previously paid invoice as unpaid.
+
+---
+
+### **MassPay.php**
+Sends payments to multiple recipients in a single API request.
+
+---
+
+### **Pay-Chained.php**
+Executes a chained payment where multiple receivers receive portions of the total amount.
+
+---
+
+### **Pay-Preapproval.php**
+Processes a payment using an existing preapproval agreement.
+
+---
+
+### **Pay.php**
+Executes a direct PayPal payment between sender and receiver.
+
+---
+
+### **PayFlowTransaction.php**
+Handles payment transactions through the PayFlow gateway system.
+
+---
+
+### **PaymentDetails.php**
+Retrieves details of a specific PayPal payment transaction.
+
+---
+
+### **PayWithOptions.php**
+Executes a payment with multiple funding options (PayPal, card, etc.).
+
+---
+
+### **Preapproval.php**
+Creates a preapproval agreement to authorize future payments automatically.
+
+---
+
+### **PreapprovalDetails.php**
+Retrieves details of a specific preapproval agreement.
+
+---
+
+### **Refund.php**
+Performs a refund for a specific PayPal payment or transaction.
+
+---
+
+### **RefundTransaction.php**
+Issues a refund for a completed transaction using its transaction ID.
+
+---
+
+### **RemindInvoice.php**
+Sends a payment reminder email for an outstanding invoice.
+
+---
+
+### **RequestPermissions.php**
+Requests permission from a PayPal user to access specific account data or actions.
+
+---
+
+### **SearchInvoices.php**
+Searches invoices based on filters such as status or date range.
+
+---
+
+### **SendInvoice.php**
+Sends an already created invoice to a recipient.
+
+---
+
+### **SetCustomerBillingAgreement.php**
+Creates a billing agreement between a customer and merchant.
+
+---
+
+### **SetExpressCheckout-Callback.php**
+Handles callback after setting up an Express Checkout session.
+
+---
+
+### **SetExpressCheckout.php**
+Initiates the Express Checkout flow for a PayPal payment.
+
+---
+
+### **SetMobileCheckout.php**
+Starts a mobile-friendly checkout session.
+
+---
+
+### **SetPaymentOptions.php**
+Sets additional payment-related options, such as shipping or recurring details.
+
+---
+
+### **TransactionSearch.php**
+Searches for transactions within a specific time period using various filters.
+
+---
+
+### **UpdateAuthorization.php**
+Updates or reauthorizes a previously held payment authorization.
+
+---
+
+### **UpdateInvoice.php**
+Updates details for an existing PayPal invoice.
+
+---
+
+### **UpdateRecurringPaymentsProfile.php**
+Updates fields or parameters of an existing recurring payment profile.
+
+---
+
+## Notes
+
+- All samples are located in the `/samples/rest/` directory.  
+- Each file demonstrates one complete PayPal API flow.  
+- **All required arguments, headers, and payload data are passed directly in the sample files.**  
+- The examples can be adapted for sandbox or live environments by changing credentials in your configuration.  
+- These methods are intended for developers to test, learn, and integrate PayPal REST APIs.
+
+---
+
+**Directory Path:**  
+`samples/rest/`
\ No newline at end of file

From ca698ac8a9d8a0833a482f6fe51e6131ddf1d18c Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Tue, 11 Nov 2025 17:30:08 +0530
Subject: [PATCH 025/146] Refund and RequestPermissions Methods Conversion

---
 samples/classic/Refund.php               | 64 ++++++++--------
 samples/classic/RequestPermissions.php   | 91 +++++++++++------------
 samples/rest/Refund.php                  | 43 +++++++++++
 samples/rest/RequestPermissions.php      | 28 +++++++
 src/angelleye/PayPal/Adaptive.php        |  8 ++
 src/angelleye/PayPal/PayPalREST.php      | 69 ++++++++++++++++++
 templates/classic/Refund.php             | 64 ++++++++--------
 templates/classic/RequestPermissions.php | 93 ++++++++++++------------
 templates/rest/Refund.php                | 43 +++++++++++
 templates/rest/RequestPermissions.php    | 28 +++++++
 10 files changed, 376 insertions(+), 155 deletions(-)
 create mode 100644 samples/rest/Refund.php
 create mode 100644 samples/rest/RequestPermissions.php
 create mode 100644 templates/rest/Refund.php
 create mode 100644 templates/rest/RequestPermissions.php

diff --git a/samples/classic/Refund.php b/samples/classic/Refund.php
index cb8287cc..93189546 100644
--- a/samples/classic/Refund.php
+++ b/samples/classic/Refund.php
@@ -3,52 +3,52 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
-
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $RefundFields = array(
-					  'CurrencyCode' => 'USD', 											// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
-					  'PayKey' => '',  													// Required.  The key used to create the payment that you want to refund.
-					  'TransactionID' => '9JK32129X69021028', 							// Required.  The PayPal transaction ID associated with the payment that you want to refund.
-					  'TrackingID' => ''												// Required.  The tracking ID associated with the payment that you want to refund.
-					  );
+	'CurrencyCode' => 'USD', 			// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+	'PayKey' => '',  				// Required.  The key used to create the payment that you want to refund.
+	'TransactionID' => '9AB88689BB076712X', 	// Required.  The PayPal transaction ID associated with the payment that you want to refund.
+	'TrackingID' => ''				// Required.  The tracking ID associated with the payment that you want to refund.
+);
 
 $Receivers = array();
 $Receiver = array(
-				  'Email' => 'agb_1296755685_biz@angelleye.com',			// A receiver's email address. 
-				  'Amount' => '100.00', 									// Amount to be debited to the receiver's account.
-				  'Primary' => '', 											// Set to true to indicate a chained payment.  Only one receiver can be a primary receiver.  Omit this field, or set to false for simple and parallel payments.
-				  'InvoiceID' => '', 										// The invoice number for the payment.  This field is only used in Pay API operation.
-				  'PaymentType' => 'GOODS'									// The transaction subtype for the payment.  Allowable values are: GOODS, SERVICE
-				  );
+	'Email' => 'agb_1296755685_biz@angelleye.com',	// A receiver's email address. 
+	'Amount' => '100.00', 				// Amount to be debited to the receiver's account.
+	'Primary' => '', 				// Set to true to indicate a chained payment.  Only one receiver can be a primary receiver.  Omit this field, or set to false for simple and parallel payments.
+	'InvoiceID' => '', 				// The invoice number for the payment.  This field is only used in Pay API operation.
+	'PaymentType' => 'GOODS'			// The transaction subtype for the payment.  Allowable values are: GOODS, SERVICE
+);
 
 array_push($Receivers, $Receiver);
 
 $PayPalRequestData = array(
-					 'RefundFields' => $RefundFields, 
-					 'Receivers' => $Receivers
-					 );
-
+	'RefundFields' => $RefundFields, 
+	'Receivers' => $Receivers
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->Refund($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->Refund($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/RequestPermissions.php b/samples/classic/RequestPermissions.php
index 45f97b50..bbb57be9 100644
--- a/samples/classic/RequestPermissions.php
+++ b/samples/classic/RequestPermissions.php
@@ -3,63 +3,64 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $Scope = array(
-				'EXPRESS_CHECKOUT', 
-				'DIRECT_PAYMENT', 
-/*				'SETTLEMENT_CONSOLIDATION', 
-				'SETTLEMENT_REPORTING', 
-				'AUTH_CAPTURE', 
-				'MOBILE_CHECKOUT', 
-*/				'BILLING_AGREEMENT', 
-				'REFERENCE_TRANSACTION', 
-/*				'AIR_TRAVEL', 
-				'MASS_PAY', 
-*/				'TRANSACTION_DETAILS',
-				'TRANSACTION_SEARCH',
-				'RECURRING_PAYMENTS',
-				'ACCOUNT_BALANCE',
-				'ENCRYPTED_WEBSITE_PAYMENTS',
-				'REFUND',
-				'NON_REFERENCED_CREDIT',
-				'BUTTON_MANAGER',
-				'MANAGE_PENDING_TRANSACTION_STATUS',
-				'RECURRING_PAYMENT_REPORT',
-				'EXTENDED_PRO_PROCESSING_REPORT',
-				'EXCEPTION_PROCESSING_REPORT',
-				'ACCOUNT_MANAGEMENT_PERMISSION',
-				'ACCESS_BASIC_PERSONAL_DATA',
-				'ACCESS_ADVANCED_PERSONAL_DATA'
-				);
+	'EXPRESS_CHECKOUT', 
+	'DIRECT_PAYMENT', 
+/*	'SETTLEMENT_CONSOLIDATION', 
+	'SETTLEMENT_REPORTING', 
+	'AUTH_CAPTURE', 
+	'MOBILE_CHECKOUT', 
+*/	'BILLING_AGREEMENT', 
+	'REFERENCE_TRANSACTION', 
+/*	'AIR_TRAVEL', 
+	'MASS_PAY', 
+*/	'TRANSACTION_DETAILS',
+	'TRANSACTION_SEARCH',
+	'RECURRING_PAYMENTS',
+	'ACCOUNT_BALANCE',
+	'ENCRYPTED_WEBSITE_PAYMENTS',
+	'REFUND',
+	'NON_REFERENCED_CREDIT',
+	'BUTTON_MANAGER',
+	'MANAGE_PENDING_TRANSACTION_STATUS',
+	'RECURRING_PAYMENT_REPORT',
+	'EXTENDED_PRO_PROCESSING_REPORT',
+	'EXCEPTION_PROCESSING_REPORT',
+	'ACCOUNT_MANAGEMENT_PERMISSION',
+	'ACCESS_BASIC_PERSONAL_DATA',
+	'ACCESS_ADVANCED_PERSONAL_DATA'
+);
 
 $RequestPermissionsFields = array(
-								'Scope' => $Scope, 				// Required.   
-								'Callback' => $domain.'paypal/class/1.4/samples/RequestPermissions-Callback.php'			// Required.  Your callback function that specifies actions to take after the account holder grants or denies the request.
-								);
+	'Scope' => $Scope, 						// Required.   
+	'Callback' => $domain . 'samples/rest/RequestPermissions.php'	// Required.  Your callback function that specifies actions to take after the account holder grants or denies the request.
+);
 
 $PayPalRequestData = array('RequestPermissionsFields' => $RequestPermissionsFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->RequestPermissions($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->RequestPermissions($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/Refund.php b/samples/rest/Refund.php
new file mode 100644
index 00000000..4a91c3ab
--- /dev/null
+++ b/samples/rest/Refund.php
@@ -0,0 +1,43 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$RefundFields = array(
+	'value' => '25.00',                            // Amount to refund.  Must not exceed the amount of the original payment.
+        'currency_code' => 'USD',        		// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+);
+
+$PayPalRequestData = array(
+	'transaction_id' => '0WU82026WU6763052', 
+	'refund_fields' => array(
+                'amount' => $RefundFields,
+                "note_to_payer" => "Refund issued"
+        ),
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->Refund($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/RequestPermissions.php b/samples/rest/RequestPermissions.php
new file mode 100644
index 00000000..e778c45d
--- /dev/null
+++ b/samples/rest/RequestPermissions.php
@@ -0,0 +1,28 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$PayPalResult = $PayPal->RequestPermissions();
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/Adaptive.php b/src/angelleye/PayPal/Adaptive.php
index ccc8dacc..c7ff8b27 100755
--- a/src/angelleye/PayPal/Adaptive.php
+++ b/src/angelleye/PayPal/Adaptive.php
@@ -40,6 +40,14 @@
 
 class Adaptive extends PayPal
 {
+	var $APISubject = '';
+	var $APIUsername = '';
+	var $APIPassword = '';
+	var $APISignature = '';
+	var $APIMode = '';
+	var $EndPointURL = '';
+	var $PrintHeaders = '';
+	var $LogResults = '';
 	var $DeveloperAccountEmail = '';
 	var $XMLNamespace = '';
 	var $ApplicationID = '';
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 7baf75a8..5d974be5 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -768,6 +768,13 @@ public function ManageSubscriptionProfile($DataArray) {
         }
     }
 
+    /**
+     * Updates an existing PayPal subscription profile using PATCH request.
+     *
+     * This method sends a PATCH request to the PayPal REST API endpoint
+     * `/v1/billing/subscriptions/{subscription_id}` to update details of an active subscription,
+     * such as plan, quantity, or metadata.
+     */
     public function UpdateSubscriptionProfile($DataArray) {
         try {
             $subscriptionId = isset($DataArray['subscription_id']) ? $DataArray['subscription_id'] : '';
@@ -797,6 +804,42 @@ public function UpdateSubscriptionProfile($DataArray) {
         }
     }
 
+    /**
+     * Issues a refund for a captured PayPal payment.
+     *
+     * This method sends a POST request to the PayPal REST API endpoint
+     * `/v2/payments/captures/{transaction_id}/refund` to process a full or partial refund
+     * for a completed payment capture.
+     */
+    public function Refund($DataArray) {
+        try {
+            $transactionId = isset($DataArray['transaction_id']) ? $DataArray['transaction_id'] : '';
+            $refundFields = isset($DataArray['refund_fields']) ? $DataArray['refund_fields'] : array();
+
+            $response = $this->makeRequest('/v2/payments/captures/' . $transactionId . '/refund', 'POST', $refundFields);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['body']['status'] ?? $response['status_code'],
+                'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Executes a PayPal Mass Payment (Payout) request using the REST API.
      *
@@ -864,6 +907,32 @@ public function GetPalDetails() {
         }
     }
 
+    public function RequestPermissions() {  
+        try {
+            $response = $this->makeRequest('/v1/identity/oauth2/userinfo?schema=openid');
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status' => $response['body']['status'] ?? $response['status_code'],
+                'full_response' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/Refund.php b/templates/classic/Refund.php
index acd81f00..16b983a0 100644
--- a/templates/classic/Refund.php
+++ b/templates/classic/Refund.php
@@ -3,52 +3,52 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
-
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $RefundFields = array(
-					  'CurrencyCode' => '', 											// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
-					  'PayKey' => '',  													// Required.  The key used to create the payment that you want to refund.
-					  'TransactionID' => '', 											// Required.  The PayPal transaction ID associated with the payment that you want to refund.
-					  'TrackingID' => ''												// Required.  The tracking ID associated with the payment that you want to refund.
-					  );
+	'CurrencyCode' => '', 		// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+	'PayKey' => '',  		// Required.  The key used to create the payment that you want to refund.
+	'TransactionID' => '', 		// Required.  The PayPal transaction ID associated with the payment that you want to refund.
+	'TrackingID' => ''		// Required.  The tracking ID associated with the payment that you want to refund.
+);
 
 $Receivers = array();
 $Receiver = array(
-				  'Email' => '',									// A receiver's email address. 
-				  'Amount' => '', 									// Amount to be debited to the receiver's account.
-				  'Primary' => '', 									// Set to true to indicate a chained payment.  Only one receiver can be a primary receiver.  Omit this field, or set to false for simple and parallel payments.
-				  'InvoiceID' => '', 								// The invoice number for the payment.  This field is only used in Pay API operation.
-				  'PaymentType' => ''								// The transaction subtype for the payment.  Allowable values are: GOODS, SERVICE
-				  );
+	'Email' => '',			// A receiver's email address. 
+	'Amount' => '', 		// Amount to be debited to the receiver's account.
+	'Primary' => '', 		// Set to true to indicate a chained payment.  Only one receiver can be a primary receiver.  Omit this field, or set to false for simple and parallel payments.
+	'InvoiceID' => '', 		// The invoice number for the payment.  This field is only used in Pay API operation.
+	'PaymentType' => ''		// The transaction subtype for the payment.  Allowable values are: GOODS, SERVICE
+);
 
 array_push($Receivers, $Receiver);
 
 $PayPalRequestData = array(
-					 'RefundFields' => $RefundFields, 
-					 'Receivers' => $Receivers
-					 );
-
+	'RefundFields' => $RefundFields, 
+	'Receivers' => $Receivers
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->Refund($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->Refund($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/RequestPermissions.php b/templates/classic/RequestPermissions.php
index 939cd1d0..517eefce 100644
--- a/templates/classic/RequestPermissions.php
+++ b/templates/classic/RequestPermissions.php
@@ -3,63 +3,64 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $Scope = array(
-				'EXPRESS_CHECKOUT', 
-				'DIRECT_PAYMENT', 
-				'SETTLEMENT_CONSOLIDATION', 
-				'SETTLEMENT_REPORTING', 
-				'AUTH_CAPTURE', 
-				'MOBILE_CHECKOUT', 
-				'BILLING_AGREEMENT', 
-				'REFERENCE_TRANSACTION', 
-				'AIR_TRAVEL', 
-				'MASS_PAY', 
-				'TRANSACTION_DETAILS',
-				'TRANSACTION_SEARCH',
-				'RECURRING_PAYMENTS',
-				'ACCOUNT_BALANCE',
-				'ENCRYPTED_WEBSITE_PAYMENTS',
-				'REFUND',
-				'NON_REFERENCED_CREDIT',
-				'BUTTON_MANAGER',
-				'MANAGE_PENDING_TRANSACTION_STATUS',
-				'RECURRING_PAYMENT_REPORT',
-				'EXTENDED_PRO_PROCESSING_REPORT',
-				'EXCEPTION_PROCESSING_REPORT',
-				'ACCOUNT_MANAGEMENT_PERMISSIONS',
-				'ACCESS_BASIC_PERSONAL_DATA',
-				'ACCESS_ADVANCED_PERSONAL_DATA'
-				);
+	'EXPRESS_CHECKOUT', 
+	'DIRECT_PAYMENT', 
+/*	'SETTLEMENT_CONSOLIDATION', 
+	'SETTLEMENT_REPORTING', 
+	'AUTH_CAPTURE', 
+	'MOBILE_CHECKOUT', 
+*/	'BILLING_AGREEMENT', 
+	'REFERENCE_TRANSACTION', 
+/*	'AIR_TRAVEL', 
+	'MASS_PAY', 
+*/	'TRANSACTION_DETAILS',
+	'TRANSACTION_SEARCH',
+	'RECURRING_PAYMENTS',
+	'ACCOUNT_BALANCE',
+	'ENCRYPTED_WEBSITE_PAYMENTS',
+	'REFUND',
+	'NON_REFERENCED_CREDIT',
+	'BUTTON_MANAGER',
+	'MANAGE_PENDING_TRANSACTION_STATUS',
+	'RECURRING_PAYMENT_REPORT',
+	'EXTENDED_PRO_PROCESSING_REPORT',
+	'EXCEPTION_PROCESSING_REPORT',
+	'ACCOUNT_MANAGEMENT_PERMISSION',
+	'ACCESS_BASIC_PERSONAL_DATA',
+	'ACCESS_ADVANCED_PERSONAL_DATA'
+);
 
 $RequestPermissionsFields = array(
-								'Scope' => $Scope, 				// Required.   
-								'Callback' => ''			// Required.  Your callback function that specifies actions to take after the account holder grants or denies the request.
-								);
-								
+	'Scope' => $Scope, 		// Required.   
+	'Callback' => ''		// Required.  Your callback function that specifies actions to take after the account holder grants or denies the request.
+);
+
 $PayPalRequestData = array('RequestPermissionsFields' => $RequestPermissionsFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->RequestPermissions($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->RequestPermissions($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/Refund.php b/templates/rest/Refund.php
new file mode 100644
index 00000000..23681ea0
--- /dev/null
+++ b/templates/rest/Refund.php
@@ -0,0 +1,43 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$RefundFields = array(
+	'value' => '',                  // Amount to refund.  Must not exceed the amount of the original payment.
+        'currency_code' => '',          // Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+);
+
+$PayPalRequestData = array(
+	'transaction_id' => '', 
+	'refund_fields' => array(
+                'amount' => array(),
+                "note_to_payer" => ''
+        ),
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->Refund($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/RequestPermissions.php b/templates/rest/RequestPermissions.php
new file mode 100644
index 00000000..e778c45d
--- /dev/null
+++ b/templates/rest/RequestPermissions.php
@@ -0,0 +1,28 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$PayPalResult = $PayPal->RequestPermissions();
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 99453621da7b19fbf62267e003df74b38be57550 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Tue, 11 Nov 2025 18:12:05 +0530
Subject: [PATCH 026/146] UpdateAuthorization Method Conversion Completed

---
 samples/classic/UpdateAuthorization.php   | 25 ++++++++---------
 samples/rest/UpdateAuthorization.php      | 26 ++++++++++++++++++
 src/angelleye/PayPal/PayPalREST.php       | 33 +++++++++++++++++++++++
 templates/classic/UpdateAuthorization.php | 32 +++++++++-------------
 templates/rest/UpdateAuthorization.php    | 26 ++++++++++++++++++
 5 files changed, 110 insertions(+), 32 deletions(-)
 create mode 100644 samples/rest/UpdateAuthorization.php
 create mode 100644 templates/rest/UpdateAuthorization.php

diff --git a/samples/classic/UpdateAuthorization.php b/samples/classic/UpdateAuthorization.php
index 44bcc853..18b06882 100644
--- a/samples/classic/UpdateAuthorization.php
+++ b/samples/classic/UpdateAuthorization.php
@@ -5,22 +5,23 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers,
-                    'LogResults' => $log_results,
-                    'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $UAFields = array(
-				'transactionid' => '3WN902700D272342K', 				// Required. The value of the authorization's transaction identification number returned by a PayPal product.  Char length: 17 single-byte chars.
-				'ipaddress' => $_SERVER['REMOTE_ADDR']					// IP address of the customer.
-				);
+	'transactionid' => '0ME934898D2880156', 		// Required. The value of the authorization's transaction identification number returned by a PayPal product.  Char length: 17 single-byte chars.
+	'ipaddress' => $_SERVER['REMOTE_ADDR']			// IP address of the customer.
+);
 				
 $PayPalRequestData = array('UAFields'=>$UAFields);
 
diff --git a/samples/rest/UpdateAuthorization.php b/samples/rest/UpdateAuthorization.php
new file mode 100644
index 00000000..56723766
--- /dev/null
+++ b/samples/rest/UpdateAuthorization.php
@@ -0,0 +1,26 @@
+ $sandbox,
+        'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$transactionID = '1G710429VE317884G';
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->UpdateAuthorization($transactionID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 5d974be5..39ff08b5 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -804,6 +804,39 @@ public function UpdateSubscriptionProfile($DataArray) {
         }
     }
 
+    /**
+     * Reauthorizes an existing PayPal payment authorization.
+     *
+     * This method sends a POST request to the PayPal REST API endpoint
+     * `/v2/payments/authorizations/{authorization_id}/reauthorize` to reauthorize
+     * a previously authorized payment before it expires.
+     */
+    public function UpdateAuthorization($transactionId)
+    {
+        try {
+            $response = $this->makeRequest('/v2/payments/authorizations/' . $transactionId . '/reauthorize', 'POST');
+
+            if ($response['status_code'] === 200) {
+                return [
+                    'success' => true,
+                    'order' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => 'Failed to get order details',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Issues a refund for a captured PayPal payment.
      *
diff --git a/templates/classic/UpdateAuthorization.php b/templates/classic/UpdateAuthorization.php
index 43462e97..580a2e14 100644
--- a/templates/classic/UpdateAuthorization.php
+++ b/templates/classic/UpdateAuthorization.php
@@ -5,30 +5,22 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					'Sandbox' => $sandbox,
-					'APIUsername' => $api_username,
-					'APIPassword' => $api_password,
-					'APISignature' => $api_signature, 
-					'PrintHeaders' => $print_headers, 
-					'LogResults' => $log_results,
-					'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
 
-$PayPal = new angelleye\PayPal\PayPal($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $UAFields = array(
-    'transactionid' => '', 				// Required. The value of the authorization's transaction identification number returned by a PayPal product.  Char length: 17 single-byte chars.
-    'ipaddress' => '',					// IP address of the customer.
-    'shiptoname' => '',
-    'shiptostreet' => '',
-    'shiptostreet2' => '',
-    'shiptocity' => '',
-    'shiptostate' => '',
-    'shiptozip' => '',
-    'shiptocountry' => '',              // Country code.
-    'shiptophonenum' => '',
-    'shiptostore' => '',                // Indicates if the item purchased will be shipped to a store location.
+	'transactionid' => '', 		// Required. The value of the authorization's transaction identification number returned by a PayPal product.  Char length: 17 single-byte chars.
+	'ipaddress' => ''   	    // IP address of the customer.
 );
 				
 $PayPalRequestData = array('UAFields'=>$UAFields);
diff --git a/templates/rest/UpdateAuthorization.php b/templates/rest/UpdateAuthorization.php
new file mode 100644
index 00000000..a75691f7
--- /dev/null
+++ b/templates/rest/UpdateAuthorization.php
@@ -0,0 +1,26 @@
+ $sandbox,
+        'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$transactionID = '';
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->UpdateAuthorization($transactionID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 26b5995dc2dfcc7d8986e03066438b9239ea3456 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 12 Nov 2025 13:36:16 +0530
Subject: [PATCH 027/146] CreateInvoice, SendInvoice and CreateAndSendInvoice
 Method Conversion Completed

---
 samples/classic/CreateAndSendInvoice.php   | 207 +++++++++++----------
 samples/classic/CreateInvoice.php          | 207 +++++++++++----------
 samples/classic/SendInvoice.php            |  34 ++--
 samples/rest/CreateAndSendInvoice.php      | 110 +++++++++++
 samples/rest/CreateInvoice.php             | 110 +++++++++++
 samples/rest/SendInvoice.php               |  30 +++
 src/angelleye/PayPal/Adaptive.php          |   1 +
 src/angelleye/PayPal/PayPalREST.php        | 134 ++++++++++++-
 templates/classic/CreateAndSendInvoice.php | 191 +++++++++----------
 templates/classic/CreateInvoice.php        | 191 +++++++++----------
 templates/classic/SendInvoice.php          |  34 ++--
 templates/rest/CreateAndSendInvoice.php    | 110 +++++++++++
 templates/rest/CreateInvoice.php           | 110 +++++++++++
 templates/rest/SendInvoice.php             |  30 +++
 14 files changed, 1068 insertions(+), 431 deletions(-)
 create mode 100644 samples/rest/CreateAndSendInvoice.php
 create mode 100644 samples/rest/CreateInvoice.php
 create mode 100644 samples/rest/SendInvoice.php
 create mode 100644 templates/rest/CreateAndSendInvoice.php
 create mode 100644 templates/rest/CreateInvoice.php
 create mode 100644 templates/rest/SendInvoice.php

diff --git a/samples/classic/CreateAndSendInvoice.php b/samples/classic/CreateAndSendInvoice.php
index 2b2111b8..ff49ce76 100644
--- a/samples/classic/CreateAndSendInvoice.php
+++ b/samples/classic/CreateAndSendInvoice.php
@@ -3,101 +3,102 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CreateInvoiceFields = array(
-							'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 				// Required.  Merchant email address.
-							'PayerEmail' => 'drew@angelleye.com', 				// Required.  Payer email address.
-							'Number' => 'ABC-ZZZz', 					// Unique ID for the invoice.
-							'CurrencyCode' => 'USD', 				// Required.  Currency used for all invoice item amounts and totals.
-							'InvoiceDate' => '', 				// Date on which the invoice is enabled.
-							'DueDate' => '', 					// Date on which the invoice payment is due.
-							'PaymentTerms' => 'DueOnReceipt', 				// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
-							'DiscountPercent' => '', 			// Discount percent applied to the invoice.
-							'DiscountAmount' => '', 			// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
-							'Terms' => '', 						// General terms for the invoice.
-							'Note' => 'This is a test invoice.', 						// Note to the payer company.
-							'MerchantMemo' => 'This is a test invoice.', 				// Memo for bookkeeping that is private to the merchant.
-							'ShippingAmount' => '10.00', 			// Cost of shipping
-							'ShippingTaxName' => '', 			// Name of the applicable tax on the shipping cost.
-							'ShippingTaxRate' => '', 			// Rate of the applicable tax on the shipping cost.
-							'LogoURL' => 'https://www.usbswiper.com/images/angelley-clients/cpp-header-image.jpg'						// Complete URL to an external image used as the logo, if any.
-							);
+	'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 				// Required.  Merchant email address.
+	'PayerEmail' => 'drew@angelleye.com', 							// Required.  Payer email address.
+	'Number' => 'ABC-ZZZz', 								// Unique ID for the invoice.
+	'CurrencyCode' => 'USD', 								// Required.  Currency used for all invoice item amounts and totals.
+	'InvoiceDate' => '', 									// Date on which the invoice is enabled.
+	'DueDate' => '', 									// Date on which the invoice payment is due.
+	'PaymentTerms' => 'DueOnReceipt', 							// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+	'DiscountPercent' => '', 								// Discount percent applied to the invoice.
+	'DiscountAmount' => '', 								// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+	'Terms' => '', 										// General terms for the invoice.
+	'Note' => 'This is a test invoice.', 							// Note to the payer company.
+	'MerchantMemo' => 'This is a test invoice.', 						// Memo for bookkeeping that is private to the merchant.
+	'ShippingAmount' => '10.00', 								// Cost of shipping
+	'ShippingTaxName' => '', 								// Name of the applicable tax on the shipping cost.
+	'ShippingTaxRate' => '', 								// Rate of the applicable tax on the shipping cost.
+	'LogoURL' => 'https://www.usbswiper.com/images/angelley-clients/cpp-header-image.jpg'	// Complete URL to an external image used as the logo, if any.
+);
 							
 $BusinessInfo = array(
-					'FirstName' => 'Tester', 							// First name of the company contact.
-					'LastName' => 'Testerson', 							// Last name of the company contact.
-					'BusinessName' => 'Testers, LLC', 						// Company business name.
-					'Phone' => '555-555-5555', 								// Phone number for contacting the company.
-					'Fax' => '555-555-5556', 								// Fax number used by the company.
-					'Website' => 'http://www.domain.com', 							// Website used by the company.
-					'Custom' => 'Some custom info.' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => 'Tester', 			// First name of the company contact.
+	'LastName' => 'Testerson', 			// Last name of the company contact.
+	'BusinessName' => 'Testers, LLC', 		// Company business name.
+	'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+	'Fax' => '555-555-5556', 			// Fax number used by the company.
+	'Website' => 'http://www.domain.com', 		// Website used by the company.
+	'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+);
 					
 $BusinessInfoAddress = array(
-							'Line1' => '123 Main St.', 						// Required. First line of address.
-							'Line2' => '', 						// Second line of address.
-							'City' => 'Grandview', 						// Required. City of the address.
-							'State' => 'MO', 						// State for the address.
-							'PostalCode' => '64030', 				// Postal code of the address
-							'CountryCode' => 'US'					// Required.  Country code of the address.
-							);
+	'Line1' => '123 Main St.', 		// Required. First line of address.
+	'Line2' => '', 				// Second line of address.
+	'City' => 'Grandview', 			// Required. City of the address.
+	'State' => 'MO', 			// State for the address.
+	'PostalCode' => '64030', 		// Postal code of the address
+	'CountryCode' => 'US'			// Required.  Country code of the address.
+);
 
 $BillingInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $BillingInfoAddress = array(
-						'Line1' => '', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => '', 						// Required. City of the address.
-						'State' => '', 						// State for the address.
-						'PostalCode' => '', 				// Postal code of the address
-						'CountryCode' => ''					// Required.  Country code of the address.
-						);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 $ShippingInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $ShippingInfoAddress = array(
-						'Line1' => '', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => '', 						// Required. City of the address.
-						'State' => '', 						// State for the address.
-						'PostalCode' => '', 				// Postal code of the address
-						'CountryCode' => ''					// Required.  Country code of the address.
-						);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
 // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
@@ -105,40 +106,40 @@
 $InvoiceItems = array();
 
 $InvoiceItem = array(
-					'Name' => 'Test Widget 1', 							// Required.  SKU or name of the item.
-					'Description' => 'This is a test widget #1', 					// Item description.
-					'Date' => '2012-02-18', 							// Date on which the product or service was provided.
-					'Quantity' => '1', 						// Required.  Item count.  Values are:  0 to 10000
-					'UnitPrice' => '10.00', 						// Required.  Price of the item, in the currency specified by the invoice.
-					'TaxName' => '', 						// Name of the applicable tax.
-					'TaxRate' => ''							// Rate of the applicable tax.
-					);
+	'Name' => 'Test Widget 1', 				// Required.  SKU or name of the item.
+	'Description' => 'This is a test widget #1', 		// Item description.
+	'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+	'Quantity' => '1', 					// Required.  Item count.  Values are:  0 to 10000
+	'UnitPrice' => '10.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+	'TaxName' => '', 					// Name of the applicable tax.
+	'TaxRate' => ''						// Rate of the applicable tax.
+);
 array_push($InvoiceItems,$InvoiceItem);
 
 $InvoiceItem = array(
-					'Name' => 'Test Widget 2', 							// Required.  SKU or name of the item.
-					'Description' => 'This is a test widget #2', 					// Item description.
-					'Date' => '2012-02-18', 							// Date on which the product or service was provided.
-					'Quantity' => '2', 						// Required.  Item count.  Values are:  0 to 10000
-					'UnitPrice' => '20.00', 						// Required.  Price of the item, in the currency specified by the invoice.
-					'TaxName' => '', 						// Name of the applicable tax.
-					'TaxRate' => ''							// Rate of the applicable tax.
-					);
+	'Name' => 'Test Widget 2', 				// Required.  SKU or name of the item.
+	'Description' => 'This is a test widget #2', 		// Item description.
+	'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+	'Quantity' => '2', 					// Required.  Item count.  Values are:  0 to 10000
+	'UnitPrice' => '20.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+	'TaxName' => '', 					// Name of the applicable tax.
+	'TaxRate' => ''						// Rate of the applicable tax.
+);
 array_push($InvoiceItems,$InvoiceItem);
 
 $PayPalRequestData = array(
-						   'CreateInvoiceFields' => $CreateInvoiceFields, 
-						   'BusinessInfo' => $BusinessInfo, 
-						   //'BusinessInfoAddress' => $BusinessInfoAddress, 
-						   //'BillingInfo' => $BillingInfo, 
-						   //'BillingInfoAddress' => $BillingInfoAddress, 
-						   //'ShippingInfo' => $ShippingInfo, 
-						   //'ShippingInfoAddress' => $ShippingInfoAddress, 
-						   'InvoiceItems' => $InvoiceItems
-						   );
+	'CreateInvoiceFields' => $CreateInvoiceFields, 
+	'BusinessInfo' => $BusinessInfo, 
+	//'BusinessInfoAddress' => $BusinessInfoAddress, 
+	//'BillingInfo' => $BillingInfo, 
+	//'BillingInfoAddress' => $BillingInfoAddress, 
+	//'ShippingInfo' => $ShippingInfo, 
+	//'ShippingInfoAddress' => $ShippingInfoAddress, 
+	'InvoiceItems' => $InvoiceItems
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateAndSendInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->CreateAndSendInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/CreateInvoice.php b/samples/classic/CreateInvoice.php
index ffe023a9..2de67f70 100644
--- a/samples/classic/CreateInvoice.php
+++ b/samples/classic/CreateInvoice.php
@@ -3,101 +3,102 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CreateInvoiceFields = array(
-							'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 				// Required.  Merchant email address.
-							'PayerEmail' => 'sandbo_1204199080_biz@angelleye.com', 				// Required.  Payer email address.
-							'Number' => '', 					// Unique ID for the invoice.
-							'CurrencyCode' => 'USD', 				// Required.  Currency used for all invoice item amounts and totals.
-							'InvoiceDate' => '', 				// Date on which the invoice is enabled.
-							'DueDate' => '', 					// Date on which the invoice payment is due.
-							'PaymentTerms' => 'DueOnReceipt', 				// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
-							'DiscountPercent' => '', 			// Discount percent applied to the invoice.
-							'DiscountAmount' => '', 			// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
-							'Terms' => '', 						// General terms for the invoice.
-							'Note' => 'This is a test invoice.', 						// Note to the payer company.
-							'MerchantMemo' => 'This is a test invoice.', 				// Memo for bookkeeping that is private to the merchant.
-							'ShippingAmount' => '10.00', 			// Cost of shipping
-							'ShippingTaxName' => '', 			// Name of the applicable tax on the shipping cost.
-							'ShippingTaxRate' => '', 			// Rate of the applicable tax on the shipping cost.
-							'LogoURL' => 'https://www.usbswiper.com/images/angelley-clients/cpp-header-image.jpg'						// Complete URL to an external image used as the logo, if any.
-							);
+	'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 				// Required.  Merchant email address.
+	'PayerEmail' => 'sandbo_1204199080_biz@angelleye.com', 					// Required.  Payer email address.
+	'Number' => '', 									// Unique ID for the invoice.
+	'CurrencyCode' => 'USD', 								// Required.  Currency used for all invoice item amounts and totals.
+	'InvoiceDate' => '', 									// Date on which the invoice is enabled.
+	'DueDate' => '', 									// Date on which the invoice payment is due.
+	'PaymentTerms' => 'DueOnReceipt', 							// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+	'DiscountPercent' => '', 								// Discount percent applied to the invoice.
+	'DiscountAmount' => '', 								// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+	'Terms' => '', 										// General terms for the invoice.
+	'Note' => 'This is a test invoice.', 							// Note to the payer company.
+	'MerchantMemo' => 'This is a test invoice.', 						// Memo for bookkeeping that is private to the merchant.
+	'ShippingAmount' => '10.00', 								// Cost of shipping
+	'ShippingTaxName' => '', 								// Name of the applicable tax on the shipping cost.
+	'ShippingTaxRate' => '', 								// Rate of the applicable tax on the shipping cost.
+	'LogoURL' => 'https://www.usbswiper.com/images/angelley-clients/cpp-header-image.jpg'	// Complete URL to an external image used as the logo, if any.
+);
 							
 $BusinessInfo = array(
-					'FirstName' => 'Tester', 							// First name of the company contact.
-					'LastName' => 'Testerson', 							// Last name of the company contact.
-					'BusinessName' => 'Testers, LLC', 						// Company business name.
-					'Phone' => '555-555-5555', 								// Phone number for contacting the company.
-					'Fax' => '555-555-5556', 								// Fax number used by the company.
-					'Website' => 'http://www.domain.com', 							// Website used by the company.
-					'Custom' => 'Some custom info.' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => 'Tester', 			// First name of the company contact.
+	'LastName' => 'Testerson', 			// Last name of the company contact.
+	'BusinessName' => 'Testers, LLC', 		// Company business name.
+	'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+	'Fax' => '555-555-5556', 			// Fax number used by the company.
+	'Website' => 'http://www.domain.com', 		// Website used by the company.
+	'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+);
 					
 $BusinessInfoAddress = array(
-							'Line1' => '123 Main St.', 						// Required. First line of address.
-							'Line2' => '', 						// Second line of address.
-							'City' => 'Grandview', 						// Required. City of the address.
-							'State' => 'MO', 						// State for the address.
-							'PostalCode' => '64030', 				// Postal code of the address
-							'CountryCode' => 'US'					// Required.  Country code of the address.
-							);
+	'Line1' => '123 Main St.', 			// Required. First line of address.
+	'Line2' => '', 					// Second line of address.
+	'City' => 'Grandview', 				// Required. City of the address.
+	'State' => 'MO', 				// State for the address.
+	'PostalCode' => '64030', 			// Postal code of the address
+	'CountryCode' => 'US'				// Required.  Country code of the address.
+);
 
 $BillingInfo = array(
-					'FirstName' => 'Tester', 							// First name of the company contact.
-					'LastName' => 'Testerson', 							// Last name of the company contact.
-					'BusinessName' => 'Testers, LLC', 						// Company business name.
-					'Phone' => '555-555-5555', 								// Phone number for contacting the company.
-					'Fax' => '555-555-5556', 								// Fax number used by the company.
-					'Website' => 'http://www.domain.com', 							// Website used by the company.
-					'Custom' => 'Some custom info.' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => 'Tester', 			// First name of the company contact.
+	'LastName' => 'Testerson', 			// Last name of the company contact.
+	'BusinessName' => 'Testers, LLC', 		// Company business name.
+	'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+	'Fax' => '555-555-5556', 			// Fax number used by the company.
+	'Website' => 'http://www.domain.com', 		// Website used by the company.
+	'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+);
 					
 $BillingInfoAddress = array(
-						'Line1' => '123 Main St.', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => 'Grandview', 						// Required. City of the address.
-						'State' => 'MO', 						// State for the address.
-						'PostalCode' => '64030', 				// Postal code of the address
-						'CountryCode' => 'US'					// Required.  Country code of the address.
-						);
+	'Line1' => '123 Main St.', 			// Required. First line of address.
+	'Line2' => '', 					// Second line of address.
+	'City' => 'Grandview', 				// Required. City of the address.
+	'State' => 'MO', 				// State for the address.
+	'PostalCode' => '64030', 			// Postal code of the address
+	'CountryCode' => 'US'				// Required.  Country code of the address.
+);
 
 $ShippingInfo = array(
-					'FirstName' => 'Tester', 							// First name of the company contact.
-					'LastName' => 'Testerson', 							// Last name of the company contact.
-					'BusinessName' => 'Testers, LLC', 						// Company business name.
-					'Phone' => '555-555-5555', 								// Phone number for contacting the company.
-					'Fax' => '555-555-5556', 								// Fax number used by the company.
-					'Website' => 'http://www.domain.com', 							// Website used by the company.
-					'Custom' => 'Some custom info.' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => 'Tester', 			// First name of the company contact.
+	'LastName' => 'Testerson', 			// Last name of the company contact.
+	'BusinessName' => 'Testers, LLC', 		// Company business name.
+	'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+	'Fax' => '555-555-5556', 			// Fax number used by the company.
+	'Website' => 'http://www.domain.com', 		// Website used by the company.
+	'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+);
 					
 $ShippingInfoAddress = array(
-						'Line1' => '123 Main St.', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => 'Grandview', 						// Required. City of the address.
-						'State' => 'MO', 						// State for the address.
-						'PostalCode' => '64030', 				// Postal code of the address
-						'CountryCode' => 'US'					// Required.  Country code of the address.
-						);
+	'Line1' => '123 Main St.', 		// Required. First line of address.
+	'Line2' => '', 				// Second line of address.
+	'City' => 'Grandview', 			// Required. City of the address.
+	'State' => 'MO', 			// State for the address.
+	'PostalCode' => '64030', 		// Postal code of the address
+	'CountryCode' => 'US'			// Required.  Country code of the address.
+);
 
 // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
 // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
@@ -105,40 +106,40 @@
 $InvoiceItems = array();
 
 $InvoiceItem = array(
-					'Name' => 'Test Widget 1', 							// Required.  SKU or name of the item.
-					'Description' => 'This is a test widget #1', 					// Item description.
-					'Date' => '2012-02-18', 							// Date on which the product or service was provided.
-					'Quantity' => '1', 						// Required.  Item count.  Values are:  0 to 10000
-					'UnitPrice' => '10.00', 						// Required.  Price of the item, in the currency specified by the invoice.
-					'TaxName' => '', 						// Name of the applicable tax.
-					'TaxRate' => ''							// Rate of the applicable tax.
-					);
+	'Name' => 'Test Widget 1', 				// Required.  SKU or name of the item.
+	'Description' => 'This is a test widget #1', 		// Item description.
+	'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+	'Quantity' => '1', 					// Required.  Item count.  Values are:  0 to 10000
+	'UnitPrice' => '10.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+	'TaxName' => '', 					// Name of the applicable tax.
+	'TaxRate' => ''						// Rate of the applicable tax.
+);
 array_push($InvoiceItems,$InvoiceItem);
 
 $InvoiceItem = array(
-					'Name' => 'Test Widget 2', 							// Required.  SKU or name of the item.
-					'Description' => 'This is a test widget #2', 					// Item description.
-					'Date' => '2012-02-18', 							// Date on which the product or service was provided.
-					'Quantity' => '2', 						// Required.  Item count.  Values are:  0 to 10000
-					'UnitPrice' => '20.00', 						// Required.  Price of the item, in the currency specified by the invoice.
-					'TaxName' => '', 						// Name of the applicable tax.
-					'TaxRate' => ''							// Rate of the applicable tax.
-					);
+	'Name' => 'Test Widget 2', 				// Required.  SKU or name of the item.
+	'Description' => 'This is a test widget #2', 		// Item description.
+	'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+	'Quantity' => '2', 					// Required.  Item count.  Values are:  0 to 10000
+	'UnitPrice' => '20.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+	'TaxName' => '', 					// Name of the applicable tax.
+	'TaxRate' => ''						// Rate of the applicable tax.
+);
 array_push($InvoiceItems,$InvoiceItem);
 
 $PayPalRequestData = array(
-						   'CreateInvoiceFields' => $CreateInvoiceFields, 
-						   'BusinessInfo' => $BusinessInfo, 
-						   'BusinessInfoAddress' => $BusinessInfoAddress, 
-						   'BillingInfo' => $BillingInfo, 
-						   'BillingInfoAddress' => $BillingInfoAddress, 
-						   'ShippingInfo' => $ShippingInfo, 
-						   'ShippingInfoAddress' => $ShippingInfoAddress, 
-						   'InvoiceItems' => $InvoiceItems
-						   );
+	'CreateInvoiceFields' => $CreateInvoiceFields, 
+	'BusinessInfo' => $BusinessInfo, 
+	'BusinessInfoAddress' => $BusinessInfoAddress, 
+	'BillingInfo' => $BillingInfo, 
+	'BillingInfoAddress' => $BillingInfoAddress, 
+	'ShippingInfo' => $ShippingInfo, 
+	'ShippingInfoAddress' => $ShippingInfoAddress, 
+	'InvoiceItems' => $InvoiceItems
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->CreateInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/SendInvoice.php b/samples/classic/SendInvoice.php
index 1ff44195..d898a71a 100644
--- a/samples/classic/SendInvoice.php
+++ b/samples/classic/SendInvoice.php
@@ -6,25 +6,27 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$InvoiceID = 'INV2-3283-QFCE-5L2E-4FCH';
-$PayPalResult = $PayPal->SendInvoice($InvoiceID);
+$InvoiceID = 'INV2-7R38-Y72Y-VBVJ-J89N';
+$PayPalResult = $PayPal->Adaptive->SendInvoice($InvoiceID);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/CreateAndSendInvoice.php b/samples/rest/CreateAndSendInvoice.php
new file mode 100644
index 00000000..87dc56fd
--- /dev/null
+++ b/samples/rest/CreateAndSendInvoice.php
@@ -0,0 +1,110 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$invoiceDetails = array(
+        "currency_code" => "USD",               // The three-character ISO 4217 currency code.
+        "note" => "This is a test invoice.",    // A note to the payer.
+        "term" => "DueOnReceipt",               // The payment term of the invoice, such as DueOnReceipt, Net30, etc.
+        "memo" => "This is a test invoice.",    // A memo for the invoice.
+);
+
+$nameData = array(
+        "given_name" => "Tester",               // The first name of the person.
+        "surname" => "Testerson"                // The last name of the person.
+);
+
+$phonesData = array(); 
+
+$phoneData = array(
+        "country_code" => "1",                  // The country code of the phone number.
+        "national_number" => "5555555555",      // The phone number without the country code.
+        "phone_type" => "MOBILE"                // The type of phone number.  Valid Values:  MOBILE, HOME, WORK, FAX.
+);
+array_push($phonesData,$phoneData);
+
+$addressData = array(
+        "address_line_1" => "123 Main St.",             // The first line of the address.
+        "admin_area_2" => "Grandview",                  // The city of the address.
+        "admin_area_1" => "MO",                         // The state of the address.
+        "postal_code" => "64030",                       // The postal code of the address.
+        "country_code" => "US"                          // The country code of the address.
+);
+
+$InvoiceItems = array();
+
+$InvoiceItem = array(
+	'name' => 'Test Widget 1', 			        // Required.  SKU or name of the item.	
+	'description' => 'This is a test widget #1', 		// Item description.
+	'quantity' => '1', 					// Required. Item count. Values are:  0 to 10000
+        'unit_amount' => array(
+                'currency_code' => 'USD',                       // The currency code.
+                'value' => '10.00'                              // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$InvoiceItem = array(
+	'name' => 'Test Widget 2', 				// Required.  SKU or name of the item.
+	'description' => 'This is a test widget #2', 		// Item description.
+	'quantity' => '2', 					// Required. Item count. Values are:  0 to 10000
+        'unit_amount' => array(
+                'currency_code' => 'USD',                       // The currency code.
+                'value' => '20.00'                              // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$configurationData = array(
+        "partial_payment" => array("allow_partial_payment" => false),   // Indicates whether to allow partial payments.  true or false.
+        "tax_calculated_after_discount" => true,                        // Indicates whether the tax amount is calculated after applying the discount.  true or false.
+        "allow_tip" => false,                                           // Indicates whether to allow the payer to add a tip to the invoice.  true or false.
+);
+
+$PayPalRequestData = array(
+        "detail" => $invoiceDetails,
+        "invoicer" => array(
+                "name" => $nameData,
+                "email_address" => "sb-j47z3s6571663@business.example.com",
+                "phones" => $phonesData,
+                "website" => "http://www.domain.com",
+                "address" => $addressData
+        ),
+        "primary_recipients" => array(
+                array(
+                        "billing_info" => array(
+                                "email_address" => "sb-j47z3s6571663@business.example.com",
+                                "name" => $nameData,
+                                "address" => $addressData
+                        ),
+                )
+        ),
+        "items" => $InvoiceItems,
+        "configuration" => $configurationData
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->CreateAndSendInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/CreateInvoice.php b/samples/rest/CreateInvoice.php
new file mode 100644
index 00000000..25f80027
--- /dev/null
+++ b/samples/rest/CreateInvoice.php
@@ -0,0 +1,110 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$invoiceDetails = array(
+        "currency_code" => "USD",               // The three-character ISO 4217 currency code.
+        "note" => "This is a test invoice.",    // A note to the payer.
+        "term" => "DueOnReceipt",               // The payment term of the invoice, such as DueOnReceipt, Net30, etc.
+        "memo" => "This is a test invoice.",    // A memo for the invoice.
+);
+
+$nameData = array(
+        "given_name" => "Tester",               // The first name of the person.
+        "surname" => "Testerson"                // The last name of the person.
+);
+
+$phonesData = array(); 
+
+$phoneData = array(
+        "country_code" => "1",                  // The country code of the phone number.
+        "national_number" => "5555555555",      // The phone number without the country code.
+        "phone_type" => "MOBILE"                // The type of phone number.  Valid Values:  MOBILE, HOME, WORK, FAX.
+);
+array_push($phonesData,$phoneData);
+
+$addressData = array(
+        "address_line_1" => "123 Main St.",             // The first line of the address.
+        "admin_area_2" => "Grandview",                  // The city of the address.
+        "admin_area_1" => "MO",                         // The state of the address.
+        "postal_code" => "64030",                       // The postal code of the address.
+        "country_code" => "US"                          // The country code of the address.
+);
+
+$InvoiceItems = array();
+
+$InvoiceItem = array(
+	'name' => 'Test Widget 1', 			        // Required.  SKU or name of the item.	
+	'description' => 'This is a test widget #1', 		// Item description.
+	'quantity' => '1', 					// Required. Item count. Values are:  0 to 10000
+        'unit_amount' => array(
+                'currency_code' => 'USD',                       // The currency code.
+                'value' => '10.00'                              // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$InvoiceItem = array(
+	'name' => 'Test Widget 2', 				// Required.  SKU or name of the item.
+	'description' => 'This is a test widget #2', 		// Item description.
+	'quantity' => '2', 					// Required. Item count. Values are:  0 to 10000
+        'unit_amount' => array(
+                'currency_code' => 'USD',                       // The currency code.
+                'value' => '20.00'                              // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$configurationData = array(
+        "partial_payment" => array("allow_partial_payment" => false),   // Indicates whether to allow partial payments.  true or false.
+        "tax_calculated_after_discount" => true,                        // Indicates whether the tax amount is calculated after applying the discount.  true or false.
+        "allow_tip" => false,                                           // Indicates whether to allow the payer to add a tip to the invoice.  true or false.
+);
+
+$PayPalRequestData = array(
+        "detail" => $invoiceDetails,
+        "invoicer" => array(
+                "name" => $nameData,
+                "email_address" => "sb-j47z3s6571663@business.example.com",
+                "phones" => $phonesData,
+                "website" => "http://www.domain.com",
+                "address" => $addressData
+        ),
+        "primary_recipients" => array(
+                array(
+                        "billing_info" => array(
+                                "email_address" => "sb-j47z3s6571663@business.example.com",
+                                "name" => $nameData,
+                                "address" => $addressData
+                        ),
+                )
+        ),
+        "items" => $InvoiceItems,
+        "configuration" => $configurationData
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->CreateInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/SendInvoice.php b/samples/rest/SendInvoice.php
new file mode 100644
index 00000000..67c1b340
--- /dev/null
+++ b/samples/rest/SendInvoice.php
@@ -0,0 +1,30 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$InvoiceID = 'INV2-G6YX-H4CK-6LUE-6JXP';
+$PayPalResult = $PayPal->SendInvoice($InvoiceID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/Adaptive.php b/src/angelleye/PayPal/Adaptive.php
index c7ff8b27..5c008e81 100755
--- a/src/angelleye/PayPal/Adaptive.php
+++ b/src/angelleye/PayPal/Adaptive.php
@@ -45,6 +45,7 @@ class Adaptive extends PayPal
 	var $APIPassword = '';
 	var $APISignature = '';
 	var $APIMode = '';
+	var $APIButtonSource = '';
 	var $EndPointURL = '';
 	var $PrintHeaders = '';
 	var $LogResults = '';
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 39ff08b5..a19a016a 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -47,7 +47,7 @@ public function test()
     /**
      * Get standard headers for API requests
      */
-    private function getHeaders($includeAuth = true, $contentType = 'application/json', $requestId = null)
+    private function getHeaders($includeAuth = true, $contentType = 'application/json', $requestId = null, $isInvoiceRequest = false)
     {
         $headers = [
         'Content-Type: ' . $contentType,
@@ -64,6 +64,10 @@ private function getHeaders($includeAuth = true, $contentType = 'application/jso
             $headers[] = 'PayPal-Request-Id: ' . $requestId;
         }
 
+        if ($isInvoiceRequest) {
+            $headers[] = 'Prefer: return=representation';
+        }
+
         return $headers;
     }
 
@@ -123,9 +127,9 @@ private function getAccessToken()
     /**
      * Make authenticated REST API request
      */
-    protected function makeRequest($endpoint, $method = 'GET', $data = null, $requestId = null)
+    protected function makeRequest($endpoint, $method = 'GET', $data = null, $requestId = null, $isInvoiceRequest = false)
     {
-        $headers = $this->getHeaders(true, 'application/json', $requestId);
+        $headers = $this->getHeaders(true, 'application/json', $requestId, $isInvoiceRequest);
 
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $this->base_url . $endpoint);
@@ -940,6 +944,13 @@ public function GetPalDetails() {
         }
     }
 
+    /**
+     * Retrieves user information using the PayPal REST Identity API.
+     *
+     * This method sends a request to the PayPal endpoint `/v1/identity/oauth2/userinfo?schema=openid`
+     * to obtain user details associated with the OAuth2 token. It processes the API response and
+     * returns success or failure based on the HTTP status code.
+     */
     public function RequestPermissions() {  
         try {
             $response = $this->makeRequest('/v1/identity/oauth2/userinfo?schema=openid');
@@ -966,6 +977,123 @@ public function RequestPermissions() {
         }
     }
 
+    /**
+     * Creates a new invoice using the PayPal Invoicing API (v2).
+     *
+     * This method sends a POST request to the `/v2/invoicing/invoices` endpoint with the provided
+     * invoice data. If successful, it returns the created invoice's ID, status, and full response.
+     */
+    public function CreateInvoice($InvoiceData)
+    {
+        try {
+            $response = $this->makeRequest('/v2/invoicing/invoices', 'POST', $InvoiceData, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'invoice_id' => $response['body']['id'] ?? null,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => 'Failed to create order',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Sends a PayPal invoice to the recipient using the PayPal Invoicing API (v2).
+     *
+     * This method triggers the sending of an existing draft invoice identified by its Invoice ID.
+     * The API endpoint `/v2/invoicing/invoices/{invoice_id}/send` is used to send the invoice
+     * to the customer via email.
+     */
+    public function SendInvoice($InvoiceID)
+    {
+        try {
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/send', 'POST', null, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Create and send a PayPal invoice using the PayPal Invoicing REST API (v2).
+     *
+     * This method first creates a new invoice using the provided invoice data, then immediately sends
+     * the created invoice to the recipient. It performs both API calls sequentially:
+     *  1. Create the invoice via `/v2/invoicing/invoices`
+     *  2. Send the created invoice via `/v2/invoicing/invoices/{invoice_id}/send`
+     */
+    public function CreateAndSendInvoice($InvoiceData)
+    {
+        $createInvoiceResponse = $this->makeRequest('/v2/invoicing/invoices', 'POST', $InvoiceData, null, true);
+
+        $responseSimplified = array();
+
+        // Check if product creation succeeded (status 2xx)
+        if ($createInvoiceResponse['status_code'] >= 200 && $createInvoiceResponse['status_code'] < 300) {
+            // Attach created product_id to the plan data
+            $InvoiceID = isset($createInvoiceResponse['body']['id']) ? $createInvoiceResponse['body']['id'] : '';
+
+            // Step 2: Create a billing plan associated with the product
+            $sendInvoiceResponse = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/send', 'POST', null, null, true);
+
+            if ($sendInvoiceResponse['status_code'] >= 200 && $sendInvoiceResponse['status_code'] < 300) {
+                $responseSimplified = array(
+                    'success' => true,
+                    'status' => !empty($sendInvoiceResponse['status_code']) ? $sendInvoiceResponse['status_code'] : 0,
+                    'response' => !empty($sendInvoiceResponse['body']) ? $sendInvoiceResponse['body'] : [],
+                    'raw_response' => !empty($sendInvoiceResponse['raw_response']) ? $sendInvoiceResponse['raw_response'] : [],
+                );
+            } else {
+                $responseSimplified = array(
+                    'success' => false,
+                    'status' => $sendInvoiceResponse['status_code'],
+                    'error' => !empty($sendInvoiceResponse['body']) ? $sendInvoiceResponse['body'] : [],
+                    'raw_response' => !empty($sendInvoiceResponse['raw_response']) ? $sendInvoiceResponse['raw_response'] : [],
+                );
+            }
+        } else {
+            $responseSimplified = array(
+                'success' => false,
+                'status' => $createInvoiceResponse['status_code'],
+                'error' => !empty($createInvoiceResponse['body']) ? $createInvoiceResponse['body'] : [],
+                'raw_response' => !empty($createInvoiceResponse['raw_response']) ? $createInvoiceResponse['raw_response'] : [],
+            );
+        }
+
+        return $responseSimplified;
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/CreateAndSendInvoice.php b/templates/classic/CreateAndSendInvoice.php
index 4bca233b..baaabd03 100644
--- a/templates/classic/CreateAndSendInvoice.php
+++ b/templates/classic/CreateAndSendInvoice.php
@@ -3,101 +3,102 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CreateInvoiceFields = array(
-							'MerchantEmail' => '', 				// Required.  Merchant email address.
-							'PayerEmail' => '', 				// Required.  Payer email address.
-							'Number' => '', 					// Unique ID for the invoice.
-							'CurrencyCode' => '', 				// Required.  Currency used for all invoice item amounts and totals.
-							'InvoiceDate' => '', 				// Date on which the invoice is enabled.
-							'DueDate' => '', 					// Date on which the invoice payment is due.
-							'PaymentTerms' => '', 				// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
-							'DiscountPercent' => '', 			// Discount percent applied to the invoice.
-							'DiscountAmount' => '', 			// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
-							'Terms' => '', 						// General terms for the invoice.
-							'Note' => '', 						// Note to the payer company.
-							'MerchantMemo' => '', 				// Memo for bookkeeping that is private to the merchant.
-							'ShippingAmount' => '', 			// Cost of shipping
-							'ShippingTaxName' => '', 			// Name of the applicable tax on the shipping cost.
-							'ShippingTaxRate' => '', 			// Rate of the applicable tax on the shipping cost.
-							'LogoURL' => ''						// Complete URL to an external image used as the logo, if any.
-							);
+	'MerchantEmail' => '', 				// Required.  Merchant email address.
+	'PayerEmail' => '', 				// Required.  Payer email address.
+	'Number' => '', 				// Unique ID for the invoice.
+	'CurrencyCode' => '', 				// Required.  Currency used for all invoice item amounts and totals.
+	'InvoiceDate' => '', 				// Date on which the invoice is enabled.
+	'DueDate' => '', 				// Date on which the invoice payment is due.
+	'PaymentTerms' => '', 				// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+	'DiscountPercent' => '', 			// Discount percent applied to the invoice.
+	'DiscountAmount' => '', 			// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+	'Terms' => '', 					// General terms for the invoice.
+	'Note' => '', 					// Note to the payer company.
+	'MerchantMemo' => '', 				// Memo for bookkeeping that is private to the merchant.
+	'ShippingAmount' => '', 			// Cost of shipping
+	'ShippingTaxName' => '', 			// Name of the applicable tax on the shipping cost.
+	'ShippingTaxRate' => '', 			// Rate of the applicable tax on the shipping cost.
+	'LogoURL' => ''					// Complete URL to an external image used as the logo, if any.
+);
 							
 $BusinessInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $BusinessInfoAddress = array(
-							'Line1' => '', 						// Required. First line of address.
-							'Line2' => '', 						// Second line of address.
-							'City' => '', 						// Required. City of the address.
-							'State' => '', 						// State for the address.
-							'PostalCode' => '', 				// Postal code of the address
-							'CountryCode' => ''					// Required.  Country code of the address.
-							);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 $BillingInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $BillingInfoAddress = array(
-						'Line1' => '', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => '', 						// Required. City of the address.
-						'State' => '', 						// State for the address.
-						'PostalCode' => '', 				// Postal code of the address
-						'CountryCode' => ''					// Required.  Country code of the address.
-						);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 $ShippingInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $ShippingInfoAddress = array(
-						'Line1' => '', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => '', 						// Required. City of the address.
-						'State' => '', 						// State for the address.
-						'PostalCode' => '', 				// Postal code of the address
-						'CountryCode' => ''					// Required.  Country code of the address.
-						);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
 // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
@@ -105,29 +106,29 @@
 $InvoiceItems = array();
 
 $InvoiceItem = array(
-					'Name' => '', 							// Required.  SKU or name of the item.
-					'Description' => '', 					// Item description.
-					'Date' => '', 							// Date on which the product or service was provided.
-					'Quantity' => '', 						// Required.  Item count.  Values are:  0 to 10000
-					'UnitPrice' => '', 						// Required.  Price of the item, in the currency specified by the invoice.
-					'TaxName' => '', 						// Name of the applicable tax.
-					'TaxRate' => ''							// Rate of the applicable tax.
-					);
+	'Name' => '', 			// Required.  SKU or name of the item.
+	'Description' => '', 		// Item description.
+	'Date' => '', 			// Date on which the product or service was provided.
+	'Quantity' => '', 		// Required.  Item count.  Values are:  0 to 10000
+	'UnitPrice' => '', 		// Required.  Price of the item, in the currency specified by the invoice.
+	'TaxName' => '', 		// Name of the applicable tax.
+	'TaxRate' => ''			// Rate of the applicable tax.
+);
 array_push($InvoiceItems,$InvoiceItem);
 
 $PayPalRequestData = array(
-						   'CreateInvoiceFields' => $CreateInvoiceFields, 
-						   'BusinessInfo' => $BusinessInfo, 
-						   'BusinessInfoAddress' => $BusinessInfoAddress, 
-						   'BillingInfo' => $BillingInfo, 
-						   'BillingInfoAddress' => $BillingInfoAddress, 
-						   'ShippingInfo' => $ShippingInfo, 
-						   'ShippingInfoAddress' => $ShippingInfoAddress, 
-						   'InvoiceItems' => $InvoiceItems
-						   );
+	'CreateInvoiceFields' => $CreateInvoiceFields, 
+	'BusinessInfo' => $BusinessInfo, 
+	'BusinessInfoAddress' => $BusinessInfoAddress, 
+	'BillingInfo' => $BillingInfo, 
+	'BillingInfoAddress' => $BillingInfoAddress, 
+	'ShippingInfo' => $ShippingInfo, 
+	'ShippingInfoAddress' => $ShippingInfoAddress, 
+	'InvoiceItems' => $InvoiceItems
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateAndSendInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->CreateAndSendInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/CreateInvoice.php b/templates/classic/CreateInvoice.php
index 19eb0110..54806f52 100644
--- a/templates/classic/CreateInvoice.php
+++ b/templates/classic/CreateInvoice.php
@@ -3,101 +3,102 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CreateInvoiceFields = array(
-							'MerchantEmail' => '', 				// Required.  Merchant email address.
-							'PayerEmail' => '', 				// Required.  Payer email address.
-							'Number' => '', 					// Unique ID for the invoice.
-							'CurrencyCode' => '', 				// Required.  Currency used for all invoice item amounts and totals.
-							'InvoiceDate' => '', 				// Date on which the invoice is enabled.
-							'DueDate' => '', 					// Date on which the invoice payment is due.
-							'PaymentTerms' => '', 				// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
-							'DiscountPercent' => '', 			// Discount percent applied to the invoice.
-							'DiscountAmount' => '', 			// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
-							'Terms' => '', 						// General terms for the invoice.
-							'Note' => '', 						// Note to the payer company.
-							'MerchantMemo' => '', 				// Memo for bookkeeping that is private to the merchant.
-							'ShippingAmount' => '', 			// Cost of shipping
-							'ShippingTaxName' => '', 			// Name of the applicable tax on the shipping cost.
-							'ShippingTaxRate' => '', 			// Rate of the applicable tax on the shipping cost.
-							'LogoURL' => ''						// Complete URL to an external image used as the logo, if any.
-							);
+	'MerchantEmail' => '', 				// Required.  Merchant email address.
+	'PayerEmail' => '', 				// Required.  Payer email address.
+	'Number' => '', 				// Unique ID for the invoice.
+	'CurrencyCode' => '', 				// Required.  Currency used for all invoice item amounts and totals.
+	'InvoiceDate' => '', 				// Date on which the invoice is enabled.
+	'DueDate' => '', 				// Date on which the invoice payment is due.
+	'PaymentTerms' => '', 				// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+	'DiscountPercent' => '', 			// Discount percent applied to the invoice.
+	'DiscountAmount' => '', 			// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+	'Terms' => '', 					// General terms for the invoice.
+	'Note' => '', 					// Note to the payer company.
+	'MerchantMemo' => '', 				// Memo for bookkeeping that is private to the merchant.
+	'ShippingAmount' => '', 			// Cost of shipping
+	'ShippingTaxName' => '', 			// Name of the applicable tax on the shipping cost.
+	'ShippingTaxRate' => '', 			// Rate of the applicable tax on the shipping cost.
+	'LogoURL' => ''					// Complete URL to an external image used as the logo, if any.
+);
 							
 $BusinessInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $BusinessInfoAddress = array(
-							'Line1' => '', 						// Required. First line of address.
-							'Line2' => '', 						// Second line of address.
-							'City' => '', 						// Required. City of the address.
-							'State' => '', 						// State for the address.
-							'PostalCode' => '', 				// Postal code of the address
-							'CountryCode' => ''					// Required.  Country code of the address.
-							);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 $BillingInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $BillingInfoAddress = array(
-						'Line1' => '', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => '', 						// Required. City of the address.
-						'State' => '', 						// State for the address.
-						'PostalCode' => '', 				// Postal code of the address
-						'CountryCode' => ''					// Required.  Country code of the address.
-						);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 $ShippingInfo = array(
-					'FirstName' => '', 							// First name of the company contact.
-					'LastName' => '', 							// Last name of the company contact.
-					'BusinessName' => '', 						// Company business name.
-					'Phone' => '', 								// Phone number for contacting the company.
-					'Fax' => '', 								// Fax number used by the company.
-					'Website' => '', 							// Website used by the company.
-					'Custom' => '' 								// Custom value to be displayed in the contact information details.
-					);
+	'FirstName' => '', 		// First name of the company contact.
+	'LastName' => '', 		// Last name of the company contact.
+	'BusinessName' => '', 		// Company business name.
+	'Phone' => '', 			// Phone number for contacting the company.
+	'Fax' => '', 			// Fax number used by the company.
+	'Website' => '', 		// Website used by the company.
+	'Custom' => '' 			// Custom value to be displayed in the contact information details.
+);
 					
 $ShippingInfoAddress = array(
-						'Line1' => '', 						// Required. First line of address.
-						'Line2' => '', 						// Second line of address.
-						'City' => '', 						// Required. City of the address.
-						'State' => '', 						// State for the address.
-						'PostalCode' => '', 				// Postal code of the address
-						'CountryCode' => ''					// Required.  Country code of the address.
-						);
+	'Line1' => '', 			// Required. First line of address.
+	'Line2' => '', 			// Second line of address.
+	'City' => '', 			// Required. City of the address.
+	'State' => '', 			// State for the address.
+	'PostalCode' => '', 		// Postal code of the address
+	'CountryCode' => ''		// Required.  Country code of the address.
+);
 
 // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
 // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
@@ -105,29 +106,29 @@
 $InvoiceItems = array();
 
 $InvoiceItem = array(
-					'Name' => '', 							// Required.  SKU or name of the item.
-					'Description' => '', 					// Item description.
-					'Date' => '', 							// Date on which the product or service was provided.
-					'Quantity' => '', 						// Required.  Item count.  Values are:  0 to 10000
-					'UnitPrice' => '', 						// Required.  Price of the item, in the currency specified by the invoice.
-					'TaxName' => '', 						// Name of the applicable tax.
-					'TaxRate' => ''							// Rate of the applicable tax.
-					);
+	'Name' => '', 			// Required.  SKU or name of the item.
+	'Description' => '', 		// Item description.
+	'Date' => '', 			// Date on which the product or service was provided.
+	'Quantity' => '', 		// Required.  Item count.  Values are:  0 to 10000
+	'UnitPrice' => '', 		// Required.  Price of the item, in the currency specified by the invoice.
+	'TaxName' => '', 		// Name of the applicable tax.
+	'TaxRate' => ''			// Rate of the applicable tax.
+);
 array_push($InvoiceItems,$InvoiceItem);
 
 $PayPalRequestData = array(
-						   'CreateInvoiceFields' => $CreateInvoiceFields, 
-						   'BusinessInfo' => $BusinessInfo, 
-						   'BusinessInfoAddress' => $BusinessInfoAddress, 
-						   'BillingInfo' => $BillingInfo, 
-						   'BillingInfoAddress' => $BillingInfoAddress, 
-						   'ShippingInfo' => $ShippingInfo, 
-						   'ShippingInfoAddress' => $ShippingInfoAddress, 
-						   'InvoiceItems' => $InvoiceItems
-						   );
+	'CreateInvoiceFields' => $CreateInvoiceFields, 
+	'BusinessInfo' => $BusinessInfo, 
+	'BusinessInfoAddress' => $BusinessInfoAddress, 
+	'BillingInfo' => $BillingInfo, 
+	'BillingInfoAddress' => $BillingInfoAddress, 
+	'ShippingInfo' => $ShippingInfo, 
+	'ShippingInfoAddress' => $ShippingInfoAddress, 
+	'InvoiceItems' => $InvoiceItems
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CreateInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->CreateInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/SendInvoice.php b/templates/classic/SendInvoice.php
index da19c21f..df4c98d6 100644
--- a/templates/classic/SendInvoice.php
+++ b/templates/classic/SendInvoice.php
@@ -6,25 +6,27 @@
 
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$InvoiceID = ''; // Required.  Invoice ID of the invoice to send.
-$PayPalResult = $PayPal->SendInvoice($InvoiceID);
+$InvoiceID = '';
+$PayPalResult = $PayPal->Adaptive->SendInvoice($InvoiceID);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/CreateAndSendInvoice.php b/templates/rest/CreateAndSendInvoice.php
new file mode 100644
index 00000000..578a1386
--- /dev/null
+++ b/templates/rest/CreateAndSendInvoice.php
@@ -0,0 +1,110 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$invoiceDetails = array(
+        "currency_code" => "",                  // The three-character ISO 4217 currency code.
+        "note" => "",                           // A note to the payer.
+        "term" => "",                           // The payment term of the invoice, such as DueOnReceipt, Net30, etc.
+        "memo" => "",                           // A memo for the invoice.
+);
+
+$nameData = array(
+        "given_name" => "",                     // The first name of the person.
+        "surname" => ""                         // The last name of the person.
+);
+
+$phonesData = array(); 
+
+$phoneData = array(
+        "country_code" => "",                   // The country code of the phone number.
+        "national_number" => "",                // The phone number without the country code.
+        "phone_type" => ""                      // The type of phone number.  Valid Values:  MOBILE, HOME, WORK, FAX.
+);
+array_push($phonesData,$phoneData);
+
+$addressData = array(
+        "address_line_1" => "",                 // The first line of the address.
+        "admin_area_2" => "",                   // The city of the address.
+        "admin_area_1" => "",                   // The state of the address.
+        "postal_code" => "",                    // The postal code of the address.
+        "country_code" => ""                    // The country code of the address.
+);
+
+$InvoiceItems = array();
+
+$InvoiceItem = array(
+	"name" => "",                           // Required.  SKU or name of the item.	
+        "description" => "", 		        // Item description.
+	"quantity" => "", 		        // Required. Item count. Values are:  0 to 10000
+        "unit_amount" => array(
+                "currency_code" => "",          // The currency code.
+                "value" => ""                   // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$InvoiceItem = array(
+	"name" => "",                           // Required.  SKU or name of the item.	
+        "description" => "", 		        // Item description.
+	"quantity" => "", 		        // Required. Item count. Values are:  0 to 10000
+        "unit_amount" => array(
+                "currency_code" => "",          // The currency code.
+                "value" => ""                   // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$configurationData = array(
+        "partial_payment" => array(),                   // Indicates whether to allow partial payments.  true or false.
+        "tax_calculated_after_discount" => "",          // Indicates whether the tax amount is calculated after applying the discount.  true or false.
+        "allow_tip" => "",                              // Indicates whether to allow the payer to add a tip to the invoice.  true or false.
+);
+
+$PayPalRequestData = array(
+        "detail" => $invoiceDetails,
+        "invoicer" => array(
+                "name" => $nameData,
+                "email_address" => "",
+                "phones" => $phonesData,
+                "website" => "",
+                "address" => $addressData
+        ),
+        "primary_recipients" => array(
+                array(
+                        "billing_info" => array(
+                                "email_address" => "",
+                                "name" => $nameData,
+                                "address" => $addressData
+                        ),
+                )
+        ),
+        "items" => $InvoiceItems,
+        "configuration" => $configurationData
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->CreateAndSendInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/CreateInvoice.php b/templates/rest/CreateInvoice.php
new file mode 100644
index 00000000..495550db
--- /dev/null
+++ b/templates/rest/CreateInvoice.php
@@ -0,0 +1,110 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$invoiceDetails = array(
+        "currency_code" => "",                  // The three-character ISO 4217 currency code.
+        "note" => "",                           // A note to the payer.
+        "term" => "",                           // The payment term of the invoice, such as DueOnReceipt, Net30, etc.
+        "memo" => "",                           // A memo for the invoice.
+);
+
+$nameData = array(
+        "given_name" => "",                     // The first name of the person.
+        "surname" => ""                         // The last name of the person.
+);
+
+$phonesData = array(); 
+
+$phoneData = array(
+        "country_code" => "",                   // The country code of the phone number.
+        "national_number" => "",                // The phone number without the country code.
+        "phone_type" => ""                      // The type of phone number.  Valid Values:  MOBILE, HOME, WORK, FAX.
+);
+array_push($phonesData,$phoneData);
+
+$addressData = array(
+        "address_line_1" => "",                 // The first line of the address.
+        "admin_area_2" => "",                   // The city of the address.
+        "admin_area_1" => "",                   // The state of the address.
+        "postal_code" => "",                    // The postal code of the address.
+        "country_code" => ""                    // The country code of the address.
+);
+
+$InvoiceItems = array();
+
+$InvoiceItem = array(
+	"name" => "",                           // Required.  SKU or name of the item.	
+        "description" => "", 		        // Item description.
+	"quantity" => "", 		        // Required. Item count. Values are:  0 to 10000
+        "unit_amount" => array(
+                "currency_code" => "",          // The currency code.
+                "value" => ""                   // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$InvoiceItem = array(
+	"name" => "",                           // Required.  SKU or name of the item.	
+        "description" => "", 		        // Item description.
+	"quantity" => "", 		        // Required. Item count. Values are:  0 to 10000
+        "unit_amount" => array(
+                "currency_code" => "",          // The currency code.
+                "value" => ""                   // The amount for the item.
+        ),
+);
+array_push($InvoiceItems,$InvoiceItem);
+
+$configurationData = array(
+        "partial_payment" => array(),                   // Indicates whether to allow partial payments.  true or false.
+        "tax_calculated_after_discount" => "",          // Indicates whether the tax amount is calculated after applying the discount.  true or false.
+        "allow_tip" => "",                              // Indicates whether to allow the payer to add a tip to the invoice.  true or false.
+);
+
+$PayPalRequestData = array(
+        "detail" => $invoiceDetails,
+        "invoicer" => array(
+                "name" => $nameData,
+                "email_address" => "",
+                "phones" => $phonesData,
+                "website" => "",
+                "address" => $addressData
+        ),
+        "primary_recipients" => array(
+                array(
+                        "billing_info" => array(
+                                "email_address" => "",
+                                "name" => $nameData,
+                                "address" => $addressData
+                        ),
+                )
+        ),
+        "items" => $InvoiceItems,
+        "configuration" => $configurationData
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->CreateInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/SendInvoice.php b/templates/rest/SendInvoice.php
new file mode 100644
index 00000000..f5a40518
--- /dev/null
+++ b/templates/rest/SendInvoice.php
@@ -0,0 +1,30 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$InvoiceID = '';
+$PayPalResult = $PayPal->SendInvoice($InvoiceID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 6cc97c0f414a18a5bc762443db35bb2d7973f0d5 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 12 Nov 2025 16:16:20 +0530
Subject: [PATCH 028/146] GetInvoiceDetails, CancelInvoice and DeleteInvoice
 Conversion Completed

---
 samples/classic/CancelInvoice.php       |  43 +++++-----
 samples/classic/DeleteInvoice.php       |  33 ++++----
 samples/classic/GetInvoiceDetails.php   |  35 ++++----
 samples/rest/CancelInvoice.php          |  37 +++++++++
 samples/rest/DeleteInvoice.php          |  31 +++++++
 samples/rest/GetInvoiceDetails.php      |  30 +++++++
 src/angelleye/PayPal/PayPalREST.php     | 104 ++++++++++++++++++++++++
 templates/classic/CancelInvoice.php     |  43 +++++-----
 templates/classic/DeleteInvoice.php     |  33 ++++----
 templates/classic/GetInvoiceDetails.php |  33 ++++----
 templates/rest/CancelInvoice.php        |  37 +++++++++
 templates/rest/DeleteInvoice.php        |  31 +++++++
 templates/rest/GetInvoiceDetails.php    |  30 +++++++
 13 files changed, 413 insertions(+), 107 deletions(-)
 create mode 100644 samples/rest/CancelInvoice.php
 create mode 100644 samples/rest/DeleteInvoice.php
 create mode 100644 samples/rest/GetInvoiceDetails.php
 create mode 100644 templates/rest/CancelInvoice.php
 create mode 100644 templates/rest/DeleteInvoice.php
 create mode 100644 templates/rest/GetInvoiceDetails.php

diff --git a/samples/classic/CancelInvoice.php b/samples/classic/CancelInvoice.php
index 54da6140..bd90ac1b 100644
--- a/samples/classic/CancelInvoice.php
+++ b/samples/classic/CancelInvoice.php
@@ -3,37 +3,38 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => '',
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CancelInvoiceFields = array(
-							'InvoiceID' => 'INV2-3283-QFCE-5L2E-4FCH', 			// ID of the invoice.
-							'Subject' => 'Invoice has been canceled.', 			// Subject of the cancelation notification.
-							'NoteForPayer' => 'Note for Payer.', 		// Note to send the payer within the cancelation notification.
-							'SendCopyToMerchant' => 'true'	// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
-							);
+	'InvoiceID' => 'INV2-3283-QFCE-5L2E-4FCH', 		// ID of the invoice.
+	'Subject' => 'Invoice has been canceled.', 		// Subject of the cancelation notification.
+	'NoteForPayer' => 'Note for Payer.', 			// Note to send the payer within the cancelation notification.
+	'SendCopyToMerchant' => 'true'				// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
+);
 
 $PayPalRequestData = array('CancelInvoiceFields' => $CancelInvoiceFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CancelInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->CancelInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/DeleteInvoice.php b/samples/classic/DeleteInvoice.php
index 59ed8097..be9ce7b2 100644
--- a/samples/classic/DeleteInvoice.php
+++ b/samples/classic/DeleteInvoice.php
@@ -3,29 +3,30 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $InvoiceID = 'INV2-YMM7-96UZ-2ZR5-HDP6';
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->DeleteInvoice($InvoiceID);
+$PayPalResult = $PayPal->Adaptive->DeleteInvoice($InvoiceID);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/GetInvoiceDetails.php b/samples/classic/GetInvoiceDetails.php
index 3e0d4e65..8f4f0f9c 100644
--- a/samples/classic/GetInvoiceDetails.php
+++ b/samples/classic/GetInvoiceDetails.php
@@ -3,28 +3,29 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$InvoiceID = 'INV2-3283-QFCE-5L2E-4FCH';
-$PayPalResult = $PayPal->GetInvoiceDetails($InvoiceID);
+$InvoiceID = 'INV2-QNBB-E86X-8437-N4U8';
+$PayPalResult = $PayPal->Adaptive->GetInvoiceDetails($InvoiceID);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/CancelInvoice.php b/samples/rest/CancelInvoice.php
new file mode 100644
index 00000000..92c867bf
--- /dev/null
+++ b/samples/rest/CancelInvoice.php
@@ -0,0 +1,37 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+	'InvoiceID' => 'INV2-PBH7-AMDJ-N3HN-GXTS', 		// ID of the invoice.
+	'Subject' => 'Invoice has been canceled.', 		// Subject of the cancelation notification.
+	'NoteForPayer' => 'Note for Payer.', 			// Note to send the payer within the cancelation notification.
+	'SendCopyToMerchant' => 'true'				// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->CancelInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/DeleteInvoice.php b/samples/rest/DeleteInvoice.php
new file mode 100644
index 00000000..461b7f3c
--- /dev/null
+++ b/samples/rest/DeleteInvoice.php
@@ -0,0 +1,31 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$InvoiceID = 'INV2-PBH7-AMDJ-N3HN-GXTS';
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->DeleteInvoice($InvoiceID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/GetInvoiceDetails.php b/samples/rest/GetInvoiceDetails.php
new file mode 100644
index 00000000..e20ac56b
--- /dev/null
+++ b/samples/rest/GetInvoiceDetails.php
@@ -0,0 +1,30 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$InvoiceID = 'INV2-7R38-Y72Y-VBVJ-J89N';
+$PayPalResult = $PayPal->GetInvoiceDetails($InvoiceID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index a19a016a..9d0ef2fc 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1094,6 +1094,110 @@ public function CreateAndSendInvoice($InvoiceData)
         return $responseSimplified;
     }
 
+    /**
+     * Retrieves detailed information about a specific PayPal invoice.
+     *
+     * This method calls the PayPal REST API endpoint `/v2/invoicing/invoices/{invoice_id}`
+     * to fetch full invoice details including status, amount, payer, and metadata.
+     */
+    public function GetInvoiceDetails($InvoiceID)
+    {
+        try {
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID, 'GET', null, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Cancels an existing PayPal invoice.
+     *
+     * This method sends a POST request to the PayPal REST API endpoint 
+     * `/v2/invoicing/invoices/{invoice_id}/cancel` to cancel a specific invoice.
+     * Optionally, it can send an email notification to both the payer and the merchant.
+     */
+    public function CancelInvoice($InvoiceData)
+    {
+        try {
+            $payload = [
+                'subject' => $InvoiceData['Subject'] ?? 'Invoice has been canceled.',
+                'note' => $InvoiceData['NoteForPayer'] ?? 'The invoice has been canceled by the merchant.',
+                'send_to_invoicer' => isset($InvoiceData['SendCopyToMerchant'])
+                    ? filter_var($InvoiceData['SendCopyToMerchant'], FILTER_VALIDATE_BOOLEAN)
+                    : true
+            ];
+
+            $InvoiceID = isset($InvoiceData['InvoiceID']) ? $InvoiceData['InvoiceID'] : '';
+
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/cancel', 'POST', $payload, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => !empty($response['body']) ? $response['body'] : ['message' => 'Invoice canceled successfully which may not return a body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => !empty($response['body']) ? $response['body'] : ['message' => 'Invoice canceled successfully which may not return a body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    public function DeleteInvoice($InvoiceID)
+    {
+        try {
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID, 'DELETE', null, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => !empty($response['body']) ? $response['body'] : ['message' => 'Invoice deleted successfully which may not return a body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => !empty($response['body']) ? $response['body'] : ['message' => 'Invoice deleted successfully which may not return a body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/CancelInvoice.php b/templates/classic/CancelInvoice.php
index b6e4fd12..e3353be9 100644
--- a/templates/classic/CancelInvoice.php
+++ b/templates/classic/CancelInvoice.php
@@ -3,37 +3,38 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $CancelInvoiceFields = array(
-							'InvoiceID' => '', 			// ID of the invoice.
-							'Subject' => '', 			// Subject of the cancelation notification.
-							'NoteForPayer' => '', 		// Note to send the payer within the cancelation notification.
-							'SendCopyToMerchant' => ''	// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
-							);
+	'InvoiceID' => '', 			// ID of the invoice.
+	'Subject' => '', 			// Subject of the cancelation notification.
+	'NoteForPayer' => '', 			// Note to send the payer within the cancelation notification.
+	'SendCopyToMerchant' => ''		// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
+);
 
 $PayPalRequestData = array('CancelInvoiceFields' => $CancelInvoiceFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->CancelInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->CancelInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/DeleteInvoice.php b/templates/classic/DeleteInvoice.php
index 9d6a06aa..1be5333d 100644
--- a/templates/classic/DeleteInvoice.php
+++ b/templates/classic/DeleteInvoice.php
@@ -3,29 +3,30 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 $InvoiceID = '';
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->DeleteInvoice($InvoiceID);
+$PayPalResult = $PayPal->Adaptive->DeleteInvoice($InvoiceID);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/GetInvoiceDetails.php b/templates/classic/GetInvoiceDetails.php
index 554d4cd8..6aa4ae13 100644
--- a/templates/classic/GetInvoiceDetails.php
+++ b/templates/classic/GetInvoiceDetails.php
@@ -3,28 +3,29 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $InvoiceID = '';
-$PayPalResult = $PayPal->GetInvoiceDetails($InvoiceID);
+$PayPalResult = $PayPal->Adaptive->GetInvoiceDetails($InvoiceID);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/CancelInvoice.php b/templates/rest/CancelInvoice.php
new file mode 100644
index 00000000..d11781e5
--- /dev/null
+++ b/templates/rest/CancelInvoice.php
@@ -0,0 +1,37 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$PayPalRequestData = array(
+	'InvoiceID' => '', 		        // ID of the invoice.
+	'Subject' => '', 		        // Subject of the cancelation notification.
+	'NoteForPayer' => '', 			// Note to send the payer within the cancelation notification.
+	'SendCopyToMerchant' => ''		// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->CancelInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/DeleteInvoice.php b/templates/rest/DeleteInvoice.php
new file mode 100644
index 00000000..5a6132f7
--- /dev/null
+++ b/templates/rest/DeleteInvoice.php
@@ -0,0 +1,31 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$InvoiceID = '';
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->DeleteInvoice($InvoiceID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/GetInvoiceDetails.php b/templates/rest/GetInvoiceDetails.php
new file mode 100644
index 00000000..44f34194
--- /dev/null
+++ b/templates/rest/GetInvoiceDetails.php
@@ -0,0 +1,30 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$InvoiceID = '';
+$PayPalResult = $PayPal->GetInvoiceDetails($InvoiceID);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From d93a1af4cf5556e55a997e0908d452b6105b7331 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 12 Nov 2025 17:34:13 +0530
Subject: [PATCH 029/146] MarkInvoiceAsPaid and MarkInvoiceAsRefunded Method
 Conversion Completed

---
 samples/classic/MarkInvoiceAsPaid.php       | 43 ++++++-----
 samples/classic/MarkInvoiceAsRefunded.php   | 41 +++++-----
 samples/rest/DeleteInvoice.php              |  2 +-
 samples/rest/MarkInvoiceAsPaid.php          | 42 ++++++++++
 samples/rest/MarkInvoiceAsRefunded.php      | 45 +++++++++++
 src/angelleye/PayPal/PayPalREST.php         | 85 +++++++++++++++++++++
 templates/classic/MarkInvoiceAsPaid.php     | 43 ++++++-----
 templates/classic/MarkInvoiceAsRefunded.php | 41 +++++-----
 templates/rest/DeleteInvoice.php            |  2 +-
 templates/rest/MarkInvoiceAsPaid.php        | 42 ++++++++++
 templates/rest/MarkInvoiceAsRefunded.php    | 45 +++++++++++
 11 files changed, 347 insertions(+), 84 deletions(-)
 create mode 100644 samples/rest/MarkInvoiceAsPaid.php
 create mode 100644 samples/rest/MarkInvoiceAsRefunded.php
 create mode 100644 templates/rest/MarkInvoiceAsPaid.php
 create mode 100644 templates/rest/MarkInvoiceAsRefunded.php

diff --git a/samples/classic/MarkInvoiceAsPaid.php b/samples/classic/MarkInvoiceAsPaid.php
index 2972a202..59ef24ee 100644
--- a/samples/classic/MarkInvoiceAsPaid.php
+++ b/samples/classic/MarkInvoiceAsPaid.php
@@ -3,37 +3,38 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MarkInvoiceAsPaidFields = array(
-								'InvoiceID' => 'INV2-GZWT-JZHS-FR3G-EDWA', 			// Required.  ID of the invoice to mark paid.
-								'Method' => 'Cash', 			// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
-								'Note' => 'This is a test note.', 				// Optional note associated with the payment.
-								'Date' => '2012-02-19'				// Date the invoice was paid.
-							);
+	'InvoiceID' => 'INV2-GZWT-JZHS-FR3G-EDWA', 		// Required.  ID of the invoice to mark paid.
+	'Method' => 'Cash', 					// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+	'Note' => 'This is a test note.', 			// Optional note associated with the payment.
+	'Date' => '2012-02-19'					// Date the invoice was paid.
+);
 
 $PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->MarkInvoiceAsPaid($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsPaid($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/MarkInvoiceAsRefunded.php b/samples/classic/MarkInvoiceAsRefunded.php
index ed61a9ea..d2c7ec11 100644
--- a/samples/classic/MarkInvoiceAsRefunded.php
+++ b/samples/classic/MarkInvoiceAsRefunded.php
@@ -3,36 +3,37 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MarkInvoiceAsRefundedFields = array(
-								'InvoiceID' => 'INV2-GZWT-JZHS-FR3G-EDWA', 			// Required.  ID of the invoice to mark paid.
-								'Note' => 'This was refunded in person via cash.', 				// Optional note associated with the payment.
-								'Date' => date('Y-m-d')				// Date the invoice was paid.
-							);
+	'InvoiceID' => 'INV2-GZWT-JZHS-FR3G-EDWA', 			// Required.  ID of the invoice to mark paid.
+	'Note' => 'This was refunded in person via cash.', 		// Optional note associated with the payment.
+	'Date' => date('Y-m-d')						// Date the invoice was paid.
+);
 
 $PayPalRequestData = array('MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->MarkInvoiceAsRefunded($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsRefunded($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/DeleteInvoice.php b/samples/rest/DeleteInvoice.php
index 461b7f3c..780707c3 100644
--- a/samples/rest/DeleteInvoice.php
+++ b/samples/rest/DeleteInvoice.php
@@ -21,7 +21,7 @@
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
-$InvoiceID = 'INV2-PBH7-AMDJ-N3HN-GXTS';
+$InvoiceID = 'INV2-PBH7-AMDJ-N3HN-GXTS';		// Invoice ID of the invoice to delete which has been cancelled
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->DeleteInvoice($InvoiceID);
diff --git a/samples/rest/MarkInvoiceAsPaid.php b/samples/rest/MarkInvoiceAsPaid.php
new file mode 100644
index 00000000..906e5719
--- /dev/null
+++ b/samples/rest/MarkInvoiceAsPaid.php
@@ -0,0 +1,42 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$MarkInvoiceAsPaidFields = array(
+	'type' => 'EXTERNAL', 		                // Required.  ID of the invoice to mark paid.
+	'method' => 'CASH', 				// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+	'note' => 'This is a test note.', 		// Optional note associated with the payment.
+	'date' => '2012-02-19'				// Date the invoice was paid.
+);
+
+$PayPalRequestData = array(
+        'InvoiceID' => 'INV2-X4CQ-CBN7-HRFF-JC9V',
+        'MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->MarkInvoiceAsPaid($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/MarkInvoiceAsRefunded.php b/samples/rest/MarkInvoiceAsRefunded.php
new file mode 100644
index 00000000..39580a9a
--- /dev/null
+++ b/samples/rest/MarkInvoiceAsRefunded.php
@@ -0,0 +1,45 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$MarkInvoiceAsRefundedFields = array(
+	'note' => 'Amount refunded to customer.',
+	'amount' => array(
+                'currency_code' => 'USD',
+                'value' => '10.00'
+	),
+	'method' => 'PAYPAL',
+	'Date' => date('Y-m-d')
+);
+
+$PayPalRequestData = array(
+	'InvoiceID' => 'INV2-X4CQ-CBN7-HRFF-JC9V',              // Invoice ID of the invoice to mark refunded which has been paid
+	'MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->MarkInvoiceAsRefunded($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 9d0ef2fc..dfa77e75 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1171,6 +1171,14 @@ public function CancelInvoice($InvoiceData)
         }
     }
 
+    /**
+     * Deletes an existing invoice from PayPal using the REST API (v2).
+     *
+     * This method sends a DELETE request to the PayPal Invoicing API endpoint to permanently 
+     * remove an invoice identified by the provided Invoice ID. 
+     * 
+     * Note: A successful DELETE operation may return an empty response body.
+     */
     public function DeleteInvoice($InvoiceID)
     {
         try {
@@ -1198,6 +1206,83 @@ public function DeleteInvoice($InvoiceID)
         }
     }
 
+    /**
+     * Marks a PayPal invoice as paid using the REST API (v2).
+     *
+     * This method records a payment against an existing PayPal invoice by sending
+     * a POST request to the `/v2/invoicing/invoices/{invoice_id}/payments` endpoint.
+     * 
+     * The provided payload should contain payment details such as the method,
+     * transaction ID, and payment date. A successful operation marks the invoice
+     * as paid and updates its status accordingly.
+     */
+    public function MarkInvoiceAsPaid($InvoiceData)
+    {
+        try {
+            $payload = !empty($InvoiceData['MarkInvoiceAsPaidFields']) ? $InvoiceData['MarkInvoiceAsPaidFields'] : [];
+            $InvoiceID = isset($InvoiceData['InvoiceID']) ? $InvoiceData['InvoiceID'] : '';
+
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/payments', 'POST', $payload, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Marks a PayPal invoice as refunded using the REST API.
+     *
+     * This method sends a POST request to the PayPal Invoicing API to record a refund 
+     * against a specific invoice. It requires the invoice ID and refund details 
+     * such as amount, note, or refund type (if applicable) in the payload.
+     */
+    public function MarkInvoiceAsRefunded($InvoiceData)
+    {
+        try {
+            $payload = !empty($InvoiceData['MarkInvoiceAsRefundedFields']) ? $InvoiceData['MarkInvoiceAsRefundedFields'] : [];
+            $InvoiceID = isset($InvoiceData['InvoiceID']) ? $InvoiceData['InvoiceID'] : '';
+
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/refunds', 'POST', $payload, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $response['body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/MarkInvoiceAsPaid.php b/templates/classic/MarkInvoiceAsPaid.php
index b6e2e5c0..edc81bde 100644
--- a/templates/classic/MarkInvoiceAsPaid.php
+++ b/templates/classic/MarkInvoiceAsPaid.php
@@ -3,37 +3,38 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MarkInvoiceAsPaidFields = array(
-								'InvoiceID' => '', 			// Required.  ID of the invoice to mark paid.
-								'Method' => '', 			// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
-								'Note' => '', 				// Optional note associated with the payment.
-								'Date' => ''				// Date the invoice was paid.
-							);
+	'InvoiceID' => '', 		// Required.  ID of the invoice to mark paid.
+	'Method' => '', 		// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+	'Note' => '', 			// Optional note associated with the payment.
+	'Date' => ''			// Date the invoice was paid.
+);
 
 $PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->MarkInvoiceAsPaid($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsPaid($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/MarkInvoiceAsRefunded.php b/templates/classic/MarkInvoiceAsRefunded.php
index 4d2fae83..d77f1bac 100644
--- a/templates/classic/MarkInvoiceAsRefunded.php
+++ b/templates/classic/MarkInvoiceAsRefunded.php
@@ -3,36 +3,37 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $MarkInvoiceAsRefundedFields = array(
-								'InvoiceID' => '', 			// Required.  ID of the invoice to mark paid.
-								'Note' => '', 				// Optional note associated with the payment.
-								'Date' => ''				// Date the invoice was paid.
-							);
+	'InvoiceID' => '', 		// Required.  ID of the invoice to mark paid.
+	'Note' => '', 			// Optional note associated with the payment.
+	'Date' => ''			// Date the invoice was paid.
+);
 
 $PayPalRequestData = array('MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->MarkInvoiceAsRefunded($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsRefunded($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/DeleteInvoice.php b/templates/rest/DeleteInvoice.php
index 5a6132f7..e690dfcc 100644
--- a/templates/rest/DeleteInvoice.php
+++ b/templates/rest/DeleteInvoice.php
@@ -21,7 +21,7 @@
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
-$InvoiceID = '';
+$InvoiceID = '';	// Invoice ID of the invoice to delete which has been cancelled
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
 $PayPalResult = $PayPal->DeleteInvoice($InvoiceID);
diff --git a/templates/rest/MarkInvoiceAsPaid.php b/templates/rest/MarkInvoiceAsPaid.php
new file mode 100644
index 00000000..572ff7e1
--- /dev/null
+++ b/templates/rest/MarkInvoiceAsPaid.php
@@ -0,0 +1,42 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$MarkInvoiceAsPaidFields = array(
+	'type' => '', 		        // Required.  ID of the invoice to mark paid.
+	'method' => '', 		// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+	'note' => '', 		        // Optional note associated with the payment.
+	'date' => ''			// Date the invoice was paid.
+);
+
+$PayPalRequestData = array(
+        'InvoiceID' => '',
+        'MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->MarkInvoiceAsPaid($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/MarkInvoiceAsRefunded.php b/templates/rest/MarkInvoiceAsRefunded.php
new file mode 100644
index 00000000..ad59b521
--- /dev/null
+++ b/templates/rest/MarkInvoiceAsRefunded.php
@@ -0,0 +1,45 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$MarkInvoiceAsRefundedFields = array(
+	'note' => '',
+	'amount' => array(
+                'currency_code' => '',
+                'value' => ''
+	),
+	'method' => '',
+	'Date' => date('Y-m-d')
+);
+
+$PayPalRequestData = array(
+	'InvoiceID' => '',                   // Invoice ID of the invoice to mark refunded which has been paid
+	'MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->MarkInvoiceAsRefunded($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From 018266c34a692a41f0b9f41204068a6552244c18 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 12 Nov 2025 18:58:50 +0530
Subject: [PATCH 030/146] Completed RemindInvoice and SearchInvoices Methods

---
 samples/classic/RemindInvoice.php    |  41 ++++----
 samples/classic/SearchInvoices.php   |  79 ++++++++-------
 samples/rest/RemindInvoice.php       |  41 ++++++++
 samples/rest/SearchInvoices.php      |  51 ++++++++++
 src/angelleye/PayPal/PayPalREST.php  | 145 +++++++++++++++++++++++++++
 templates/classic/RemindInvoice.php  |  41 ++++----
 templates/classic/SearchInvoices.php |  79 ++++++++-------
 templates/rest/RemindInvoice.php     |  41 ++++++++
 templates/rest/SearchInvoices.php    |  51 ++++++++++
 9 files changed, 451 insertions(+), 118 deletions(-)
 create mode 100644 samples/rest/RemindInvoice.php
 create mode 100644 samples/rest/SearchInvoices.php
 create mode 100644 templates/rest/RemindInvoice.php
 create mode 100644 templates/rest/SearchInvoices.php

diff --git a/samples/classic/RemindInvoice.php b/samples/classic/RemindInvoice.php
index 289a6628..03a71578 100644
--- a/samples/classic/RemindInvoice.php
+++ b/samples/classic/RemindInvoice.php
@@ -3,36 +3,37 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $RemindInvoiceFields = array(
-							'InvoiceID' => 'INV2-NV29-RP49-7ERJ-8L6C', 			// ID of the invoice.
-							'Subject' => 'This is the subject.', 			// Subject of the cancelation notification.
-							'NoteForPayer' => 'This is a note to the payer.' 		// Note to send the payer within the cancelation notification.
-							);
+	'InvoiceID' => 'INV2-NV29-RP49-7ERJ-8L6C', 			// ID of the invoice.
+	'Subject' => 'This is the subject.', 				// Subject of the cancelation notification.
+	'NoteForPayer' => 'This is a note to the payer.' 		// Note to send the payer within the cancelation notification.
+);
 
 $PayPalRequestData = array('RemindInvoiceFields' => $RemindInvoiceFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->RemindInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->RemindInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/classic/SearchInvoices.php b/samples/classic/SearchInvoices.php
index b6866605..73c684f7 100644
--- a/samples/classic/SearchInvoices.php
+++ b/samples/classic/SearchInvoices.php
@@ -3,56 +3,57 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject,
-                      'PrintHeaders' => $print_headers, 
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
-
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $SearchInvoicesFields = array(
-							'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 			// Required.  Email address of invoice creator.
-							'Page' => '1', 					// Required.  Page number of result set, starting with 1
-							'PageSize' => '1'				// Required.  Number of result pages, between 1 and 100
-							);
+	'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 		// Required.  Email address of invoice creator.
+	'Page' => '1', 								// Required.  Page number of result set, starting with 1
+	'PageSize' => '1'							// Required.  Number of result pages, between 1 and 100
+);
 
 $Parameters = array(
-					'Email' => '', 															// Email search string
-					'RecipientName' => '', 													// Recipient search string
-					'BusinessName' => '', 													// Company search string
-					'InvoiceNumber' => '', 													// Invoice number search string
-					'Status' => '', 														// Invoice status search
-					'LowerAmount' => '', 													// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
-					'UpperAmount' => '', 													// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
-					'CurrencyCode' => '', 													// Currency used for lower and upper amounts.  
-					'Memo' => '', 															// Invoice memo search string
-					'Origin' => '' 														// Indicates whether the invoice was created by the website or by an API call.  Values are:  Web, API
-					//'InvoiceDate' => array('StartDate' => '', 'EndDate' => ''), 			// Invoice date range filter
-					//'DueDate' => array('StartDate' => '', 'EndDate' => ''), 				// Invoice due Date range filter
-					//'PaymentDate' => array('StartDate' => '', 'EndDate' => ''), 			// Invoice payment date range filter.
-					//'CreationDate' => array('StartDate' => '', 'EndDate' => '')				// Invoice creation date range filter.
-					);
+	'Email' => '', 								// Email search string
+	'RecipientName' => '', 							// Recipient search string
+	'BusinessName' => '', 							// Company search string
+	'InvoiceNumber' => '', 							// Invoice number search string
+	'Status' => '', 							// Invoice status search
+	'LowerAmount' => '', 							// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'UpperAmount' => '', 							// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'CurrencyCode' => '', 							// Currency used for lower and upper amounts.  
+	'Memo' => '', 								// Invoice memo search string
+	'Origin' => '' 								// Indicates whether the invoice was created by the website or by an API call.  Values are:  Web, API
+	//'InvoiceDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice date range filter
+	//'DueDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice due Date range filter
+	//'PaymentDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice payment date range filter.
+	//'CreationDate' => array('StartDate' => '', 'EndDate' => '')		// Invoice creation date range filter.
+);
 
 $PayPalRequestData = array(
-						   'SearchInvoicesFields' => $SearchInvoicesFields, 
-						   'Parameters' => $Parameters
-						   );
+	'SearchInvoicesFields' => $SearchInvoicesFields, 
+	'Parameters' => $Parameters
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->SearchInvoices($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->SearchInvoices($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/samples/rest/RemindInvoice.php b/samples/rest/RemindInvoice.php
new file mode 100644
index 00000000..26536ade
--- /dev/null
+++ b/samples/rest/RemindInvoice.php
@@ -0,0 +1,41 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$RemindInvoiceFields = array(
+        'subject' => 'This is the subject.', 			// Subject of the cancelation notification.
+	'note' => 'This is a note to the payer.' 		// Note to send the payer within the cancelation notification.
+);
+
+$PayPalRequestData = array(
+        'InvoiceID' => 'INV2-2HKE-U26U-9AAF-LN6B',
+        'RemindInvoiceFields' => $RemindInvoiceFields
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->RemindInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/samples/rest/SearchInvoices.php b/samples/rest/SearchInvoices.php
new file mode 100644
index 00000000..dfe3c227
--- /dev/null
+++ b/samples/rest/SearchInvoices.php
@@ -0,0 +1,51 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$SearchInvoicesFields = array(
+        'Page' => '1', 								// Required.  Page number of result set, starting with 1
+	'PageSize' => '20'							// Required.  Number of result pages, between 1 and 100
+);
+
+$Parameters = array(
+        'Email' => '', 								// Email search string
+        'MerchantEmail' => '',                                   		// Required.  Email address of invoice creator.
+	'InvoiceNumber' => '', 							// Invoice number search string
+	'Status' => 'DRAFT', 							// Invoice status search
+	'LowerAmount' => '', 							// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'UpperAmount' => '', 							// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'CurrencyCode' => '', 							// Currency used for lower and upper amounts.  
+	'Memo' => '', 								// Invoice memo search string
+);
+
+$PayPalRequestData = array(
+	'SearchInvoicesFields' => $SearchInvoicesFields, 
+	'Parameters' => $Parameters
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->SearchInvoices($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index dfa77e75..55cabe9e 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1283,6 +1283,151 @@ public function MarkInvoiceAsRefunded($InvoiceData)
         }
     }
 
+    /**
+     * Sends a reminder for a specific invoice using the PayPal REST API.
+     *
+     * This method triggers a reminder email to the recipient of the specified invoice.
+     * It makes a POST request to the `/v2/invoicing/invoices/{invoice_id}/remind` endpoint.
+     */
+    public function RemindInvoice($InvoiceData)
+    {
+        try {
+            $payload = !empty($InvoiceData['RemindInvoiceFields']) ? $InvoiceData['RemindInvoiceFields'] : [];
+            $InvoiceID = isset($InvoiceData['InvoiceID']) ? $InvoiceData['InvoiceID'] : '';
+
+            $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/remind', 'POST', $payload, null, true);
+
+            if ($response['status_code'] === 201) {
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => !empty($response['body']) ? $response['body'] : ['message' => 'Invoice reminder sent successfully which may not return a body']
+                ];
+            }
+
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => !empty($response['body']) ? $response['body'] : ['message' => 'Invoice reminder sent successfully which may not return a body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
+    }
+
+    /**
+     * Searches and filters PayPal invoices using REST API.
+     *
+     * This method retrieves a paginated list of invoices from the PayPal Invoicing API
+     * and applies optional filters such as status, email, currency, amount range, and memo.
+     * It supports client-side filtering using the provided `$Parameters` array.
+     */
+    public function SearchInvoices($InvoiceData)
+    {
+        try {
+            $SearchInvoicesFields = !empty($InvoiceData['SearchInvoicesFields']) ? $InvoiceData['SearchInvoicesFields'] : [];
+            $Parameters = !empty($InvoiceData['Parameters']) ? $InvoiceData['Parameters'] : [];
+
+            $page = isset($SearchInvoicesFields['Page']) ? $SearchInvoicesFields['Page'] : 1;
+            $page_size = isset($SearchInvoicesFields['PageSize']) ? $SearchInvoicesFields['PageSize'] : 20;
+
+            // Build query parameters for filtering
+            $query = [];
+
+            // Pagination parameters
+            $query['page'] = $page;
+            $query['page_size'] = $page_size;
+
+            // Build the query string
+            $query_string = http_build_query($query);
+
+            // Make REST API request
+            $response = $this->makeRequest('/v2/invoicing/invoices?' . $query_string, 'GET', null, null, true);
+
+            if (in_array($response['status_code'], [200, 201])) {
+                $invoices = $response['body']['items'];
+
+                $filteredInvoices = array_filter($invoices, function ($invoice) use ($Parameters) {
+                    $statusMatch = true;
+                    $emailMatch = true;
+                    $invoiceEmailMatch = true;
+                    $invoiceNumberMatch = true;
+                    $currencyMatch = true;
+                    $amountMatch = true;
+                    $memoMatch = true;
+
+                    // Filter: Status
+                    if (!empty($Parameters['Status'])) {
+                        $statusMatch = isset($invoice['status']) && strtoupper($invoice['status']) === strtoupper($Parameters['Status']);
+                    }
+
+                    // Filter: Email
+                    if (!empty($Parameters['Email'])) {
+                        $recipientEmail = $invoice['primary_recipients'][0]['billing_info']['email_address'] ?? '';
+                        $emailMatch = strcasecmp($recipientEmail, $Parameters['Email']) === 0;
+                    }
+
+                    // Filter: Invoicer email
+                    if (!empty($Parameters['MerchantEmail'])) {
+                        $invoicerEmail = $invoice['invoicer']['email_address'] ?? '';
+                        $emailMatch = strcasecmp($invoicerEmail, $Parameters['MerchantEmail']) === 0;
+                    }
+
+                    // Filter: Invoice number
+                    if (!empty($Parameters['InvoiceNumber'])) {
+                        $invoiceNumberMatch = isset($invoice['detail']['invoice_number']) && $invoice['detail']['invoice_number'] == $Parameters['InvoiceNumber'];
+                    }
+
+                    // Filter: Currency code
+                    if (!empty($Parameters['CurrencyCode'])) {
+                        $currencyMatch = isset($invoice['detail']['currency_code']) && $invoice['detail']['currency_code'] == $Parameters['CurrencyCode'];
+                    }
+
+                    // Filter: Amount range
+                    if (!empty($Parameters['LowerAmount']) || !empty($Parameters['UpperAmount'])) {
+                        $total = $invoice['amount']['value'] ?? 0;
+                        $lower = $Parameters['LowerAmount'] ?? 0;
+                        $upper = $Parameters['UpperAmount'] ?? 999999;
+                        $amountMatch = ($total >= $lower && $total <= $upper);
+                    }
+
+                    // Filter: Memo (check detail.note or similar)
+                    if (!empty($Parameters['Memo'])) {
+                        $memo = $invoice['detail']['note'] ?? '';
+                        $memoMatch = stripos($memo, $Parameters['Memo']) !== false;
+                    }
+
+                    // Must satisfy all filters
+                    return $statusMatch && $emailMatch && $invoiceEmailMatch && $invoiceNumberMatch && $currencyMatch && $amountMatch && $memoMatch;
+                });
+
+                return [
+                    'success' => true,
+                    'status_code' => $response['status_code'],
+                    'total_items' => count($filteredInvoices),
+                    'invoices' => array_values($filteredInvoices),
+                ];
+            }
+
+            return [
+                'success' => false,
+                'status_code' => $response['status_code'],
+                'message' => $response['body']['message'] ?? 'Unknown error',
+                'full_response' => $response['body']
+            ];
+        } catch (Exception $e) {
+            return [
+                'success' => false,
+                'status_code' => 500,
+                'message' => $e->getMessage(),
+            ];
+        }
+    }
+
     /**
      * Test Orders API functionality
      */
diff --git a/templates/classic/RemindInvoice.php b/templates/classic/RemindInvoice.php
index 839458c8..cabb9429 100644
--- a/templates/classic/RemindInvoice.php
+++ b/templates/classic/RemindInvoice.php
@@ -3,36 +3,37 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
 
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $RemindInvoiceFields = array(
-							'InvoiceID' => '', 			// ID of the invoice.
-							'Subject' => '', 			// Subject of the reminder notification.
-							'NoteForPayer' => '' 		// Note to send the payer within the reminder notification.
-							);
+	'InvoiceID' => '', 		// ID of the invoice.
+	'Subject' => '', 		// Subject of the reminder notification.
+	'NoteForPayer' => '' 		// Note to send the payer within the reminder notification.
+);
 
 $PayPalRequestData = array('RemindInvoiceFields' => $RemindInvoiceFields);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->RemindInvoice($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->RemindInvoice($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/classic/SearchInvoices.php b/templates/classic/SearchInvoices.php
index af1fe969..5283d68c 100644
--- a/templates/classic/SearchInvoices.php
+++ b/templates/classic/SearchInvoices.php
@@ -3,56 +3,57 @@
 require_once('../../includes/config.php');
 require_once('../../autoload.php');
 
-
 // Create PayPal object.
 $PayPalConfig = array(
-					  'Sandbox' => $sandbox,
-					  'DeveloperAccountEmail' => $developer_account_email,
-					  'ApplicationID' => $application_id,
-					  'DeviceID' => $device_id,
-					  'IPAddress' => $_SERVER['REMOTE_ADDR'],
-					  'APIUsername' => $api_username,
-					  'APIPassword' => $api_password,
-					  'APISignature' => $api_signature,
-					  'APISubject' => $api_subject, 
-					  'PrintHeaders' => $print_headers,
-					  'LogResults' => $log_results, 
-					  'LogPath' => $log_path,
-					);
-
-$PayPal = new angelleye\PayPal\Adaptive($PayPalConfig);
+	'Sandbox' => $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
 // Prepare request arrays
 $SearchInvoicesFields = array(
-							'MerchantEmail' => '', 			// Required.  Email address of invoice creator.
-							'Page' => '', 					// Required.  Page number of result set, starting with 1
-							'PageSize' => ''				// Required.  Number of result pages, between 1 and 100
-							);
+	'MerchantEmail' => '', 			// Required.  Email address of invoice creator.
+	'Page' => '', 				// Required.  Page number of result set, starting with 1
+	'PageSize' => ''			// Required.  Number of result pages, between 1 and 100
+);
 
 $Parameters = array(
-					'Email' => '', 															// Email search string
-					'RecipientName' => '', 													// Recipient search string
-					'BusinessName' => '', 													// Company search string
-					'InvoiceNumber' => '', 													// Invoice number search string
-					'Status' => '', 														// Invoice status search
-					'LowerAmount' => '', 													// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
-					'UpperAmount' => '', 													// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
-					'CurrencyCode' => '', 													// Currency used for lower and upper amounts.  
-					'Memo' => '', 															// Invoice memo search string
-					'Origin' => '', 														// Indicates whether the invoice was created by the website or by an API call.  Values are:  Web, API
-					'InvoiceDate' => array('StartDate' => '', 'EndDate' => ''), 			// Invoice date range filter
-					'DueDate' => array('StartDate' => '', 'EndDate' => ''), 				// Invoice due Date range filter
-					'PaymentDate' => array('StartDate' => '', 'EndDate' => ''), 			// Invoice payment date range filter.
-					'CreationDate' => array('StartDate' => '', 'EndDate' => '')				// Invoice creation date range filter.
-					);
+	'Email' => '', 								// Email search string
+	'RecipientName' => '', 							// Recipient search string
+	'BusinessName' => '', 							// Company search string
+	'InvoiceNumber' => '', 							// Invoice number search string
+	'Status' => '', 							// Invoice status search
+	'LowerAmount' => '', 							// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'UpperAmount' => '', 							// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'CurrencyCode' => '', 							// Currency used for lower and upper amounts.  
+	'Memo' => '', 								// Invoice memo search string
+	'Origin' => '' 								// Indicates whether the invoice was created by the website or by an API call.  Values are:  Web, API
+	//'InvoiceDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice date range filter
+	//'DueDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice due Date range filter
+	//'PaymentDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice payment date range filter.
+	//'CreationDate' => array('StartDate' => '', 'EndDate' => '')		// Invoice creation date range filter.
+);
 
 $PayPalRequestData = array(
-						   'SearchInvoicesFields' => $SearchInvoicesFields, 
-						   'Parameters' => $Parameters
-						   );
+	'SearchInvoicesFields' => $SearchInvoicesFields, 
+	'Parameters' => $Parameters
+);
 
 // Pass data into class for processing with PayPal and load the response array into $PayPalResult
-$PayPalResult = $PayPal->SearchInvoices($PayPalRequestData);
+$PayPalResult = $PayPal->Adaptive->SearchInvoices($PayPalRequestData);
 
 // Write the contents of the response array to the screen for demo purposes.
 echo '
';
diff --git a/templates/rest/RemindInvoice.php b/templates/rest/RemindInvoice.php
new file mode 100644
index 00000000..dbd6c08b
--- /dev/null
+++ b/templates/rest/RemindInvoice.php
@@ -0,0 +1,41 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$RemindInvoiceFields = array(
+        'subject' => '', 		// Subject of the cancelation notification.
+	'note' => '' 		        // Note to send the payer within the cancelation notification.
+);
+
+$PayPalRequestData = array(
+        'InvoiceID' => '',
+        'RemindInvoiceFields' => $RemindInvoiceFields
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->RemindInvoice($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/rest/SearchInvoices.php b/templates/rest/SearchInvoices.php
new file mode 100644
index 00000000..f1e97f59
--- /dev/null
+++ b/templates/rest/SearchInvoices.php
@@ -0,0 +1,51 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$SearchInvoicesFields = array(
+        'Page' => '', 								// Required.  Page number of result set, starting with 1
+	'PageSize' => ''							// Required.  Number of result pages, between 1 and 100
+);
+
+$Parameters = array(
+        'Email' => '', 								// Email search string
+        'MerchantEmail' => '',                                   		// Required.  Email address of invoice creator.
+	'InvoiceNumber' => '', 							// Invoice number search string
+	'Status' => '', 							// Invoice status search
+	'LowerAmount' => '', 							// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'UpperAmount' => '', 							// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+	'CurrencyCode' => '', 							// Currency used for lower and upper amounts.  
+	'Memo' => '', 								// Invoice memo search string
+);
+
+$PayPalRequestData = array(
+	'SearchInvoicesFields' => $SearchInvoicesFields, 
+	'Parameters' => $Parameters
+);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->SearchInvoices($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From a82427377e4091c98d2abb620cec2067056b05a1 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Thu, 13 Nov 2025 16:31:06 +0530
Subject: [PATCH 031/146] Added Upgrade Flag and Converted GetBalance Mapping

---
 samples/sample-methods/GetBalance.php | 32 +++++++++++
 src/angelleye/PayPal/PayPalREST.php   | 83 ++++++++++++++++++---------
 2 files changed, 87 insertions(+), 28 deletions(-)
 create mode 100644 samples/sample-methods/GetBalance.php

diff --git a/samples/sample-methods/GetBalance.php b/samples/sample-methods/GetBalance.php
new file mode 100644
index 00000000..e35db8a7
--- /dev/null
+++ b/samples/sample-methods/GetBalance.php
@@ -0,0 +1,32 @@
+ $sandbox,
+        'PayPalAPIMode' => $api_mode,
+        'PayPalAPIUpgrade' => $api_upgrade,
+        'APIUsername' => $api_username,
+        'APIPassword' => $api_password,
+        'APISignature' => $api_signature,
+        'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+        'PrintHeaders' => $print_headers,
+        'LogResults' => $log_results,
+        'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$GBFields = array('returnallcurrencies' => '');
+$PayPalRequestData = array('GBFields'=>$GBFields);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetBalance($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 55cabe9e..37cef8c5 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -13,6 +13,7 @@ class PayPalREST extends PayPal
     private $tokenExpiry;
     private $client_id;
     private $client_secret;
+    private $api_upgrade;
     private $base_url;
 
     public function __construct($config)
@@ -27,6 +28,7 @@ public function __construct($config)
         // Set REST-specific credentials
         $this->client_id = isset($config['ClientID']) ? $config['ClientID'] : '';
         $this->client_secret = isset($config['ClientSecret']) ? $config['ClientSecret'] : '';
+        $this->api_upgrade = isset($config['PayPalAPIUpgrade']) ? $config['PayPalAPIUpgrade'] : FALSE;
 
         // Parent class already handles: sandbox, print_headers, log_results, log_path, base URLs
     }
@@ -161,39 +163,64 @@ protected function makeRequest($endpoint, $method = 'GET', $data = null, $reques
      */
     function GetBalance($DataArray)
     {
-        $returnAllCurrencies = !empty($DataArray['GBFields']['returnallcurrencies']) ? true : false;
-
-        $response = $this->makeRequest('/v1/reporting/balances');
-
-        $responseSimplified = [
-            'ASOFTIME' => !empty($response['body']['as_of_time']) ? $response['body']['as_of_time'] : '',
-            'ACCOUNTID' => !empty($response['body']['account_id']) ? $response['body']['account_id'] : '',
-            'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
-            'ERRORS' => [],
-            'BALANCES' => [],
-            'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : '',
-        ];
+        try {
+            $response = $this->makeRequest('/v1/reporting/balances');
 
-        // Capture errors if available
-        if (!empty($response['body']['errors']) && is_array($response['body']['errors'])) {
-            $responseSimplified['errors'] = $response['body']['errors'];
-        }
+            if (in_array($response['status_code'], [200, 201])) {
+                $body = $response['body'];
+
+                if ($this->api_upgrade) {
+                    $balances = [];
+                    $flatBalances = [];
+
+                    if (!empty($body['balances'])) {
+                        foreach ($body['balances'] as $i => $bal) {
+                            $amount = $bal['total_balance']['value'];
+                            $currency = $bal['currency'];
+
+                            // Add to BALANCERESULTS array (Classic-style)
+                            $balances[] = [
+                                'L_AMT' => $amount,
+                                'L_CURRENCYCODE' => $currency,
+                            ];
+
+                            // Also add to flattened keys (L_AMT0, L_AMT1, ...)
+                            $flatBalances["L_AMT{$i}"] = $amount;
+                            $flatBalances["L_CURRENCYCODE{$i}"] = $currency;
+                        }
+                    }
 
-        if (!empty($response['body']['balances']) && is_array($response['body']['balances'])) {
-            foreach ($response['body']['balances'] as $balance) {
-                if ($returnAllCurrencies || !empty($balance['primary'])) {
-                    $responseSimplified['BALANCES'][] = [
-                        'CURRENCY' => !empty($balance['currency']) ? $balance['currency'] : '',
-                        'TOTALBALANCE' => !empty($balance['total_balance']['value']) ? $balance['total_balance']['value'] : 0,
-                        'AVAILABLEBALANCE' => !empty($balance['available_balance']['value']) ? $balance['available_balance']['value'] : 0,
-                        'WITHHELDBALANCE' => !empty($balance['withheld_balance']['value']) ? $balance['withheld_balance']['value'] : 0,
-                        'PRIMARY' => !empty($balance['primary']) ? 1 : 0,
-                    ];
+                    return array_merge(
+                        $flatBalances,
+                        [
+                            'TIMESTAMP' => $body['as_of_time'] ?? gmdate('c'),
+                            'ACK' => 'Success',
+                            'BALANCERESULTS' => $balances,
+                            'RAWRESPONSE' => $response['raw_response'] ?? [],
+                        ]
+                    );
                 }
+
+                // Normal REST-style response
+                return [
+                    'success' => true,
+                    'status' => $response['body']['status'] ?? $response['status_code'],
+                    'full_response' => $body,
+                ];
             }
-        }
 
-        return $responseSimplified;
+            return [
+                'success' => false,
+                'error' => '',
+                'status_code' => $response['body']['status'] ?? $response['status_code'],
+                'details' => $response['body']
+            ];
+        } catch (\Exception $e) {
+            return [
+                'success' => false,
+                'error' => $e->getMessage()
+            ];
+        }
     }
 
     function AddBankAccount($DataArray) {

From b88e61d0aa365599bf2b33eedc8d4282a4a42ca7 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Fri, 14 Nov 2025 21:38:33 +0530
Subject: [PATCH 032/146] SetExpressCheckout, GetExpressCheckout and
 DoExpresCheckout Method Conversion Completed

---
 samples/rest/DoExpressCheckoutPayment.php     |  19 +-
 samples/rest/SetExpressCheckout.php           | 207 ++++++++--
 .../DoExpressCheckoutPayment.php              | 163 ++++++++
 samples/sample-methods/SetExpressCheckout.php | 192 +++++++++
 src/angelleye/PayPal/Adaptive.php             |   6 +
 src/angelleye/PayPal/PayPalClassic.php        |   2 +-
 src/angelleye/PayPal/PayPalREST.php           | 383 +++++++++++++++++-
 7 files changed, 913 insertions(+), 59 deletions(-)
 create mode 100644 samples/sample-methods/DoExpressCheckoutPayment.php
 create mode 100644 samples/sample-methods/SetExpressCheckout.php

diff --git a/samples/rest/DoExpressCheckoutPayment.php b/samples/rest/DoExpressCheckoutPayment.php
index e30f7527..7b4a919c 100644
--- a/samples/rest/DoExpressCheckoutPayment.php
+++ b/samples/rest/DoExpressCheckoutPayment.php
@@ -5,6 +5,7 @@
 $PayPalConfig = array(
 	'Sandbox' => $sandbox,
 	'PayPalAPIMode' => $api_mode,
+	'PayPalAPIUpgrade' => $api_upgrade,
 	'ClientID' => $rest_client_id,
 	'ClientSecret' => $rest_client_secret,
 	'PrintHeaders' => $print_headers,
@@ -14,9 +15,19 @@
 
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
-$orderId = isset($_GET['token']) ? $_GET['token'] : '';
+$orderId = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+	$orderId = isset($_SESSION['SetExpressCheckoutResult']['order_id']) ? $_SESSION['SetExpressCheckoutResult']['order_id'] : '';
+} else {
+	$orderId = isset($_SESSION['SetExpressCheckoutResult']['TOKEN']) ? $_SESSION['SetExpressCheckoutResult']['TOKEN'] : '';
+}
 
-$PaymentResult = $PayPal->captureOrder($orderId);
+$GECDResults = $PayPal->getOrder($orderId);
+echo 'GetExpressCheckoutDetails
';
+print_r($GECDResults);
+echo '

'; -echo '
';
-print_r($PaymentResult);
\ No newline at end of file
+$PaymentResult = $PayPal->captureOrder($orderId);
+echo 'DoExpressCheckout
';
+print_r($PaymentResult);
+echo '

'; \ No newline at end of file diff --git a/samples/rest/SetExpressCheckout.php b/samples/rest/SetExpressCheckout.php index edcc0c74..e4f7a56a 100644 --- a/samples/rest/SetExpressCheckout.php +++ b/samples/rest/SetExpressCheckout.php @@ -7,6 +7,7 @@ $PayPalConfig = array( 'Sandbox' => $sandbox, 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, 'ClientID' => $rest_client_id, 'ClientSecret' => $rest_client_secret, 'APIVersion' => '97.0', @@ -18,51 +19,171 @@ $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); -$orderData = [ - 'intent' => 'CAPTURE', // or 'AUTHORIZE' if you plan to capture later - 'purchase_units' => [ - [ - 'reference_id' => 'ORDER-' . uniqid(), - 'amount' => [ - 'currency_code' => 'USD', - 'value' => '50.00', - 'breakdown' => [ - 'item_total' => [ - 'currency_code' => 'USD', - 'value' => '50.00' - ] - ] - ], - 'items' => [ - [ - 'name' => 'Sample Product', - 'unit_amount' => [ - 'currency_code' => 'USD', - 'value' => '25.00' - ], - 'quantity' => '2' - ] - ] - ] - ], - 'application_context' => [ - 'brand_name' => 'Angell EYE', - 'landing_page' => 'LOGIN', // or 'BILLING' for guest checkout - 'user_action' => 'CONTINUE', - 'return_url' => $domain . 'samples/rest/DoExpressCheckoutPayment.php', - 'cancel_url' => $domain . 'samples/rest/', - ] -]; +$SECFields = array( + 'token' => '', // A timestamped token, the value of which was returned by a previous SetExpressCheckout call. + 'maxamt' => '200.00', // The expected maximum total amount the order will be, including S&H and sales tax. + 'returnurl' => $domain . 'samples/rest/DoExpressCheckoutPayment.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => $domain . 'samples/rest/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'callback' => '', // URL to which the callback request from PayPal is sent. Must start with https:// for production. + 'callbacktimeout' => '', // An override for you to request more or less time to be able to process the callback request and response. Acceptable range for override is 1-6 seconds. If you specify greater than 6 PayPal will use default value of 3 seconds. + 'callbackversion' => '', // The version of the Instant Update API you're using. The default is the current version. + 'reqconfirmshipping' => '0', // The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal. This overrides anything in the account profile. Possible values are 1 or 0. + 'noshipping' => '1', // The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed. Maybe 1 or 0. + 'addroverride' => '', // The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal. This does not allow the customer to edit the address here. Must be 1 or 0. + 'localecode' => '', // Locale of pages displayed by PayPal during checkout. Should be a 2 character country code. You can retrive the country code by passing the country name into the class' GetCountryCode() function. + 'pagestyle' => '', // Sets the Custom Payment Page Style for payment pages associated with this button/link. + 'hdrimg' => '', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. + 'hdrbordercolor' => '', // Sets the border color around the header of the payment page. The border is a 2-pixel permiter around the header space. Default is black. + 'hdrbackcolor' => '', // Sets the background color for the header of the payment page. Default is white. + 'payflowcolor' => '', // Sets the background color for the payment page. Default is white. + 'skipdetails' => '', // This is a custom field not included in the PayPal documentation. It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not. See PayPal docs for more info. + 'email' => '', // Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal sign-in page. 127 char max. + 'solutiontype' => 'Sole', // Type of checkout flow. Must be Sole (express checkout for auctions) or Mark (normal express checkout) + 'landingpage' => 'Billing', // Type of PayPal page to display. Can be Billing or Login. If billing it shows a full credit card form. If Login it just shows the login screen. + 'channeltype' => '', // Type of channel. Must be Merchant (non-auction seller) or eBayItem (eBay auction) + 'giropaysuccessurl' => '', // The URL on the merchant site to redirect to after a successful giropay payment. Only use this field if you are using giropay or bank transfer payment methods in Germany. + 'giropaycancelurl' => '', // The URL on the merchant site to redirect to after a canceled giropay payment. Only use this field if you are using giropay or bank transfer methods in Germany. + 'banktxnpendingurl' => '', // The URL on the merchant site to transfer to after a bank transfter payment. Use this field only if you are using giropay or bank transfer methods in Germany. + 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. + 'customerservicenumber' => '555-555-5555', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. + 'giftmessageenable' => '1', // Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1 + 'giftreceiptenable' => '1', // Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1 + 'giftwrapenable' => '1', // Enable gift wrap widget on the PayPal Review page. Allowable values are 0 and 1. + 'giftwrapname' => 'Box with Ribbon', // Label for the gift wrap option such as "Box with ribbon". 25 char max. + 'giftwrapamount' => '2.50', // Amount charged for gift-wrap service. + 'buyeremailoptionenable' => '1', // Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1 + 'surveyquestion' => '', // Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present. 50 char max. + 'surveyenable' => '1', // Enable survey functionality. Allowable values are 0 and 1 + 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max. + 'buyerusername' => '', // The user name of the user at the marketplaces site. + 'buyerregistrationdate' => '2012-07-14T00:00:00Z', // Date when the user registered with the marketplace. + 'allowpushfunding' => '' // Whether the merchant can accept push funding. 0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding. +); + +// Basic array of survey choices. Nothing but the values should go in here. +$SurveyChoices = array('Yes', 'No'); + +$Payments = array(); +$Payment = array( + 'amt' => '100.00', // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'currencycode' => 'USD', // A three-character currency code. Default is USD. + 'itemamt' => '80.00', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. + 'shippingamt' => '15.00', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount. If true, the total shipping insurance for this order must be a positive number. + 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => '5.00', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'desc' => 'This is a test order.', // Description of items on the order. 127 char max. + 'custom' => '', // Free-form field for your own use. 256 char max. + 'invnum' => '', // Your own invoice or tracking number. 127 char max. + 'notifyurl' => '', // URL for receiving Instant Payment Notifications + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '', // Phone number for shipping address. 20 char max. + 'notetext' => 'This is a test note before ever having left the web site.', // Note to the merchant. 255 char max. + 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. + 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. + 'paymentrequestid' => '', // A unique identifier of the specific payment request, which is required for parallel payments. + 'sellerpaypalaccountid' => '' // A unique identifier for the merchant. For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant. +); + +$PaymentOrderItems = array(); +$Item = array( + 'name' => 'Widget 123', // Item name. 127 char max. + 'desc' => 'Widget 123', // Item description. 127 char max. + 'amt' => '40.00', // Cost of item. + 'number' => '123', // Item number. 127 char max. + 'qty' => '1', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => 'http://www.angelleye.com/products/123.php', // URL for the item. + 'itemcategory' => '', // One of the following values: Digital, Physical + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); +array_push($PaymentOrderItems, $Item); + +$Item = array( + 'name' => 'Widget 456', // Item name. 127 char max. + 'desc' => 'Widget 456', // Item description. 127 char max. + 'amt' => '40.00', // Cost of item. + 'number' => '456', // Item number. 127 char max. + 'qty' => '1', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => 'http://www.angelleye.com/products/456.php', // URL for the item. + 'itemcategory' => 'Digital', // One of the following values: Digital, Physical + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); +array_push($PaymentOrderItems, $Item); -$PaymentResult = $PayPal->createOrder($orderData); +$Payment['order_items'] = $PaymentOrderItems; +array_push($Payments, $Payment); -if ($PaymentResult['success']) { - $_SESSION['paypal_order_id'] = $PaymentResult['order_id']; +$BuyerDetails = array( + 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. Char max 255. + 'buyerusername' => '', // The username of the marketplace site. + 'buyerregistrationdate' => '' // The registration of the buyer with the marketplace. +); + +// For shipping options we create an array of all shipping choices similar to how order items works. +$ShippingOptions = array(); +$Option = array( + 'l_shippingoptionisdefault' => '', // Shipping option. Required if specifying the Callback URL. true or false. Must be only 1 default! + 'l_shippingoptionname' => '', // Shipping option name. Required if specifying the Callback URL. 50 character max. + 'l_shippingoptionlabel' => '', // Shipping option label. Required if specifying the Callback URL. 50 character max. + 'l_shippingoptionamount' => '' // Shipping option amount. Required if specifying the Callback URL. +); +array_push($ShippingOptions, $Option); + +$BillingAgreements = array(); +$Item = array( + 'l_billingtype' => 'MerchantInitiatedBilling', // Required. Type of billing agreement. For recurring payments it must be RecurringPayments. You can specify up to ten billing agreements. For reference transactions, this field must be either: MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource + 'l_billingagreementdescription' => 'Billing Agreement', // Required for recurring payments. Description of goods or services associated with the billing agreement. + 'l_paymenttype' => 'Any', // Specifies the type of PayPal payment you require for the billing agreement. Any or IntantOnly + 'l_billingagreementcustom' => '' // Custom annotation field for your own use. 256 char max. +); +array_push($BillingAgreements, $Item); - echo 'Click here to continue.

'; - - echo '
';
-	print_r($PaymentResult);
+$PayPalRequest = array(
+	'SECFields' => $SECFields, 
+	'SurveyChoices' => $SurveyChoices, 
+	'BillingAgreements' => $BillingAgreements, 
+	'Payments' => $Payments
+);
+
+$_SESSION['SetExpressCheckoutResult'] = $PayPal->SetExpressCheckout($PayPalRequest);
+
+$redirect_url = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+    $redirect_url = $_SESSION['SetExpressCheckoutResult']['approval_url'];
 } else {
-    	echo 'Error creating order: ' . $PaymentResult['error'];
+    $redirect_url = $_SESSION['SetExpressCheckoutResult']['REDIRECTURL'];
 }
+
+echo 'Click here to continue.

'; +echo '
';
+print_r($_SESSION['SetExpressCheckoutResult']);
diff --git a/samples/sample-methods/DoExpressCheckoutPayment.php b/samples/sample-methods/DoExpressCheckoutPayment.php
new file mode 100644
index 00000000..a0569f70
--- /dev/null
+++ b/samples/sample-methods/DoExpressCheckoutPayment.php
@@ -0,0 +1,163 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+        'PayPalAPIUpgrade' => $api_upgrade,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$orderId = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+	$orderId = $_SESSION['SetExpressCheckoutResult']['order_id'];
+} else {
+	$orderId = $_SESSION['SetExpressCheckoutResult']['TOKEN'];
+}
+
+$payerID = '';
+
+$DECPFields = array(
+	'token' => $orderId, 	// Required.  A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'payerid' => $payerID, 				// Required.  Unique PayPal customer id of the payer.  Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL.
+	'returnfmfdetails' => '1', 					// Flag to indicate whether you want the results returned by Fraud Management Filters or not.  1 or 0.
+	'giftmessage' => '', 						// The gift message entered by the buyer on the PayPal Review page.  150 char max.
+	'giftreceiptenable' => '', 					// Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false.
+	'giftwrapname' => '', 						// The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer.
+	'giftwrapamount' => '', 					// The amount only if the gift option on the PayPal Review page was selected by the buyer.
+	'buyermarketingemail' => '', 					// The buyer email address opted in by the buyer on the PayPal Review page.
+	'surveyquestion' => '', 					// The survey question on the PayPal Review page.  50 char max.
+	'surveychoiceselected' => '',  					// The survey response selected by the buyer on the PayPal Review page.  15 char max.
+	'allowedpaymentmethod' => '', 					// The payment method type. Specify the value InstantPaymentOnly.
+	'buttonsource' => '' 						// ID code for use by third-party apps to identify transactions in PayPal. 
+);
+						
+$Payments = array();
+$Payment = array(
+	'amt' => '100.00', 								// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+	'currencycode' => 'USD', 							// A three-character currency code.  Default is USD.
+	'itemamt' => '80.00', 								// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
+	'shippingamt' => '15.00', 							// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+	'insuranceoptionoffered' => '', 						// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+	'handlingamt' => '', 								// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+	'taxamt' => '5.00', 								// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
+	'desc' => 'This is a test order.', 						// Description of items on the order.  127 char max.
+	'custom' => '', 								// Free-form field for your own use.  256 char max.
+	'invnum' => '', 								// Your own invoice or tracking number.  127 char max.
+	'notifyurl' => '',  								// URL for receiving Instant Payment Notifications
+	'shiptoname' => '', 								// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 								// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 								// Second street address.  100 char max.
+	'shiptocity' => '', 								// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 								// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 								// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 								// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => '',  							// Phone number for shipping address.  20 char max.
+	'notetext' => 'This is a test note before ever having left the web site.', 	// Note to the merchant.  255 char max.  
+	'allowedpaymentmethod' => '', 							// The payment method type.  Specify the value InstantPaymentOnly.
+	'paymentaction' => 'Sale', 							// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
+	'paymentrequestid' => '',  							// A unique identifier of the specific payment request, which is required for parallel payments. 
+	'sellerpaypalaccountid' => ''							// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+);
+				
+$PaymentOrderItems = array();
+$Item = array(
+	'name' => 'Widget 123', 					// Item name. 127 char max.
+	'desc' => 'Widget 123', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '123', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/123.php', 	// URL for the item.
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Item = array(
+	'name' => 'Widget 456', 					// Item name. 127 char max.
+	'desc' => 'Widget 456', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '456', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/456.php', 	// URL for the item.
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Payment['order_items'] = $PaymentOrderItems;
+array_push($Payments, $Payment);				
+
+$UserSelectedOptions = array(
+	'shippingcalculationmode' => '', 	// Describes how the options that were presented to the user were determined.  values are:  API - Callback   or   API - Flatrate.
+	'insuranceoptionselected' => '', 	// The Yes/No option that you chose for insurance.
+	'shippingoptionisdefault' => '', 	// Is true if the buyer chose the default shipping option.  
+	'shippingoptionamount' => '', 		// The shipping amount that was chosen by the buyer.
+	'shippingoptionname' => '', 		// Is true if the buyer chose the default shipping option...??  Maybe this is supposed to show the name..??
+);
+
+$GetExpressCheckoutRequest = array(
+	'DECPFields' => $DECPFields, 
+	'Payments' => $Payments
+);
+
+/*
+ * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal
+ */
+if ( $api_mode === 'rest' ) {
+        $GECDResult = $PayPal->GetExpressCheckoutDetails($GetExpressCheckoutRequest);
+} else {
+        $GECDResult = $PayPal->GetExpressCheckoutDetails($orderId);
+}
+echo 'GetExpressCheckoutDetails
';
+print_r($GECDResult);
+echo '

'; + +if ( $api_mode === 'rest' && ! $api_upgrade ) { + $payerID = isset($GECDResult['order']['payer']['payer_id']) ? $GECDResult['order']['payer']['payer_id'] : ''; +} else { + $payerID = $GECDResult['PAYERID']; +} + +$DECPFields['payerid'] = $payerID; + +$PayPalRequest = array( + 'DECPFields' => $DECPFields, + 'Payments' => $Payments +); + +$_SESSION['PayPalResult'] = $PayPal->DoExpressCheckoutPayment($PayPalRequest); +echo 'DoExpressCheckout
';
+print_r($_SESSION['PayPalResult']);
diff --git a/samples/sample-methods/SetExpressCheckout.php b/samples/sample-methods/SetExpressCheckout.php
new file mode 100644
index 00000000..296f08db
--- /dev/null
+++ b/samples/sample-methods/SetExpressCheckout.php
@@ -0,0 +1,192 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+        'PayPalAPIUpgrade' => $api_upgrade,
+        'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'APIVersion' => '97.0', 
+	'APISubject' => '',
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$SECFields = array(
+	'token' => '', 								// A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'maxamt' => '200.00', 							// The expected maximum total amount the order will be, including S&H and sales tax.
+	'returnurl' => $domain . 'samples/sample-methods/DoExpressCheckoutPayment.php',	// Required.  URL to which the customer will be returned after returning from PayPal.  2048 char max.
+	'cancelurl' => $domain . 'samples/sample-methods/',	 			// Required.  URL to which the customer will be returned if they cancel payment on PayPal's site.
+	'callback' => '', 							// URL to which the callback request from PayPal is sent.  Must start with https:// for production.
+	'callbacktimeout' => '', 						// An override for you to request more or less time to be able to process the callback request and response.  Acceptable range for override is 1-6 seconds.  If you specify greater than 6 PayPal will use default value of 3 seconds.
+	'callbackversion' => '', 						// The version of the Instant Update API you're using.  The default is the current version.							
+	'reqconfirmshipping' => '0', 						// The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal.  This overrides anything in the account profile.  Possible values are 1 or 0.
+	'noshipping' => '1', 							// The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed.  Maybe 1 or 0.					
+	'addroverride' => '', 							// The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal.  This does not allow the customer to edit the address here.  Must be 1 or 0.
+	'localecode' => '', 							// Locale of pages displayed by PayPal during checkout.  Should be a 2 character country code.  You can retrive the country code by passing the country name into the class' GetCountryCode() function.
+	'pagestyle' => '', 							// Sets the Custom Payment Page Style for payment pages associated with this button/link.  
+	'hdrimg' => '', 							// URL for the image displayed as the header during checkout.  Max size of 750x90.  Should be stored on an https:// server or you'll get a warning message in the browser.
+	'hdrbordercolor' => '', 						// Sets the border color around the header of the payment page.  The border is a 2-pixel permiter around the header space.  Default is black.  
+	'hdrbackcolor' => '', 							// Sets the background color for the header of the payment page.  Default is white.  
+	'payflowcolor' => '', 							// Sets the background color for the payment page.  Default is white.
+	'skipdetails' => '', 							// This is a custom field not included in the PayPal documentation.  It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not.  See PayPal docs for more info.
+	'email' => '', 								// Email address of the buyer as entered during checkout.  PayPal uses this value to pre-fill the PayPal sign-in page.  127 char max.
+	'solutiontype' => 'Sole', 						// Type of checkout flow.  Must be Sole (express checkout for auctions) or Mark (normal express checkout)
+	'landingpage' => 'Billing', 						// Type of PayPal page to display.  Can be Billing or Login.  If billing it shows a full credit card form.  If Login it just shows the login screen.
+	'channeltype' => '', 							// Type of channel.  Must be Merchant (non-auction seller) or eBayItem (eBay auction)
+	'giropaysuccessurl' => '', 						// The URL on the merchant site to redirect to after a successful giropay payment.  Only use this field if you are using giropay or bank transfer payment methods in Germany.
+	'giropaycancelurl' => '', 						// The URL on the merchant site to redirect to after a canceled giropay payment.  Only use this field if you are using giropay or bank transfer methods in Germany.
+	'banktxnpendingurl' => '',  						// The URL on the merchant site to transfer to after a bank transfter payment.  Use this field only if you are using giropay or bank transfer methods in Germany.
+	'brandname' => 'Angell EYE', 						// A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.  127 char max.
+	'customerservicenumber' => '555-555-5555', 				// Merchant Customer Service number displayed on the PayPal Review page. 16 char max.
+	'giftmessageenable' => '1', 						// Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftreceiptenable' => '1', 						// Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1
+	'giftwrapenable' => '1', 						// Enable gift wrap widget on the PayPal Review page.  Allowable values are 0 and 1.
+	'giftwrapname' => 'Box with Ribbon', 					// Label for the gift wrap option such as "Box with ribbon".  25 char max.
+	'giftwrapamount' => '2.50', 						// Amount charged for gift-wrap service.
+	'buyeremailoptionenable' => '1', 					// Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1
+	'surveyquestion' => '', 						// Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present.  50 char max.
+	'surveyenable' => '1', 							// Enable survey functionality. Allowable values are 0 and 1
+	'buyerid' => '', 							// The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max.
+	'buyerusername' => '', 							// The user name of the user at the marketplaces site.
+	'buyerregistrationdate' => '2012-07-14T00:00:00Z',  			// Date when the user registered with the marketplace.
+	'allowpushfunding' => ''						// Whether the merchant can accept push funding.  0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding.			
+);
+
+// Basic array of survey choices.  Nothing but the values should go in here.  
+$SurveyChoices = array('Yes', 'No');
+
+$Payments = array();
+$Payment = array(
+	'amt' => '100.00', 									// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+	'currencycode' => 'USD', 								// A three-character currency code.  Default is USD.
+	'itemamt' => '80.00', 									// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
+	'shippingamt' => '15.00', 								// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+	'insuranceoptionoffered' => '', 							// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+	'handlingamt' => '', 									// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+	'taxamt' => '5.00', 									// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
+	'desc' => 'This is a test order.', 							// Description of items on the order.  127 char max.
+	'custom' => '', 									// Free-form field for your own use.  256 char max.
+	'invnum' => '', 									// Your own invoice or tracking number.  127 char max.
+	'notifyurl' => '',  									// URL for receiving Instant Payment Notifications
+	'shiptoname' => '', 									// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 									// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 									// Second street address.  100 char max.
+	'shiptocity' => '', 									// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 									// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 									// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 									// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => '',  								// Phone number for shipping address.  20 char max.
+	'notetext' => 'This is a test note before ever having left the web site.', 		// Note to the merchant.  255 char max.  
+	'allowedpaymentmethod' => '', 								// The payment method type.  Specify the value InstantPaymentOnly.
+	'paymentaction' => 'Sale', 								// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
+	'paymentrequestid' => '',  								// A unique identifier of the specific payment request, which is required for parallel payments. 
+	'sellerpaypalaccountid' => ''								// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+);
+				
+$PaymentOrderItems = array();
+$Item = array(
+	'name' => 'Widget 123', 					// Item name. 127 char max.
+	'desc' => 'Widget 123', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '123', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/123.php',	// URL for the item.
+	'itemcategory' => '', 						// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Item = array(
+	'name' => 'Widget 456', 					// Item name. 127 char max.
+	'desc' => 'Widget 456', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '456', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/456.php', 	// URL for the item.
+	'itemcategory' => 'Digital', 					// One of the following values:  Digital, Physical
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Payment['order_items'] = $PaymentOrderItems;
+array_push($Payments, $Payment);
+
+$BuyerDetails = array(
+	'buyerid' => '', 		// The unique identifier provided by eBay for this buyer.  The value may or may not be the same as the username.  In the case of eBay, it is different.  Char max 255.
+	'buyerusername' => '', 		// The username of the marketplace site.
+	'buyerregistrationdate' => ''	// The registration of the buyer with the marketplace.
+);
+						
+// For shipping options we create an array of all shipping choices similar to how order items works.
+$ShippingOptions = array();
+$Option = array(
+	'l_shippingoptionisdefault' => '', 		// Shipping option.  Required if specifying the Callback URL.  true or false.  Must be only 1 default!
+	'l_shippingoptionname' => '', 			// Shipping option name.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionlabel' => '', 			// Shipping option label.  Required if specifying the Callback URL.  50 character max.
+	'l_shippingoptionamount' => '' 			// Shipping option amount.  Required if specifying the Callback URL.  
+);
+array_push($ShippingOptions, $Option);
+		
+$BillingAgreements = array();
+$Item = array(
+	'l_billingtype' => 'MerchantInitiatedBilling', 				// Required.  Type of billing agreement.  For recurring payments it must be RecurringPayments.  You can specify up to ten billing agreements.  For reference transactions, this field must be either:  MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource
+	'l_billingagreementdescription' => 'Billing Agreement', 		// Required for recurring payments.  Description of goods or services associated with the billing agreement.  
+	'l_paymenttype' => 'Any', 						// Specifies the type of PayPal payment you require for the billing agreement.  Any or IntantOnly
+	'l_billingagreementcustom' => ''					// Custom annotation field for your own use.  256 char max.
+);
+array_push($BillingAgreements, $Item);
+
+$PayPalRequest = array(
+	'SECFields' => $SECFields, 
+	'SurveyChoices' => $SurveyChoices, 
+	'BillingAgreements' => $BillingAgreements, 
+	'Payments' => $Payments
+);
+
+$_SESSION['SetExpressCheckoutResult'] = $PayPal->SetExpressCheckout($PayPalRequest);
+
+$redirect_url = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+    $redirect_url = $_SESSION['SetExpressCheckoutResult']['approval_url'];
+} else {
+    $redirect_url = $_SESSION['SetExpressCheckoutResult']['REDIRECTURL'];
+}
+
+echo 'Click here to continue.

'; +echo '
';
+print_r($_SESSION['SetExpressCheckoutResult']);
diff --git a/src/angelleye/PayPal/Adaptive.php b/src/angelleye/PayPal/Adaptive.php
index 5c008e81..97bb81a7 100755
--- a/src/angelleye/PayPal/Adaptive.php
+++ b/src/angelleye/PayPal/Adaptive.php
@@ -67,6 +67,12 @@ class Adaptive extends PayPal
 	function __construct($DataArray)
 	{
 		parent::__construct($DataArray);
+
+		if (isset($DataArray['Sandbox'])) {
+			$this->Sandbox = $DataArray['Sandbox'];
+		} else {
+			$this->Sandbox = false;
+		}
 		
 		$this->XMLNamespace = 'http://svcs.paypal.com/types/ap';
 		$this->DeviceID = isset($DataArray['DeviceID']) ? $DataArray['DeviceID'] : '';
diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
index 24c3c0fd..c3f9df2a 100644
--- a/src/angelleye/PayPal/PayPalClassic.php
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -82,7 +82,7 @@ function __construct($DataArray)
         if (isset($DataArray['Sandbox'])) {
             $this->Sandbox = $DataArray['Sandbox'];
         } else {
-            $this->Sandbox = true;
+            $this->Sandbox = false;
         }
 
         if (isset($DataArray['isAdaptive'])) {
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 37cef8c5..06a2ff72 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -193,10 +193,10 @@ function GetBalance($DataArray)
                     return array_merge(
                         $flatBalances,
                         [
-                            'TIMESTAMP' => $body['as_of_time'] ?? gmdate('c'),
+                            'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
                             'ACK' => 'Success',
                             'BALANCERESULTS' => $balances,
-                            'RAWRESPONSE' => $response['raw_response'] ?? [],
+                            'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
                         ]
                     );
                 }
@@ -417,7 +417,8 @@ public function createOrder($orderData)
                     'order_id' => $response['body']['id'],
                     'status' => $response['body']['status'] ?? $response['status_code'],
                     'approval_url' => $this->getApprovalUrl($response['body']['links']),
-                    'full_response' => $response['body']
+                    'full_response' => $response['body'],
+                    'raw_response' => $response['raw_response']
                 ];
             }
 
@@ -425,7 +426,8 @@ public function createOrder($orderData)
                 'success' => false,
                 'error' => 'Failed to create order',
                 'status_code' => $response['body']['status'] ?? $response['status_code'],
-                'details' => $response['body']
+                'details' => $response['body'],
+                'raw_response' => $response['raw_response']
             ];
         } catch (\Exception $e) {
             return [
@@ -446,15 +448,17 @@ public function getOrder($orderId)
             if ($response['status_code'] === 200) {
                 return [
                     'success' => true,
-                    'order' => $response['body']
+                    'order' => $response['body'],
+                    'raw_response' => $response['raw_response']
                 ];
             }
-
+            
             return [
                 'success' => false,
                 'error' => 'Failed to get order details',
                 'status_code' => $response['body']['status'] ?? $response['status_code'],
-                'details' => $response['body']
+                'details' => $response['body'],
+                'raw_response' => $response['raw_response']
             ];
         } catch (\Exception $e) {
             return [
@@ -477,7 +481,8 @@ public function authorizeOrder($orderId)
                     'success' => true,
                     'authorization_id' => $response['body']['purchase_units'][0]['payments']['authorizations'][0]['id'],
                     'status' => $response['body']['status'] ?? $response['status_code'],
-                    'full_response' => $response['body']
+                    'full_response' => $response['body'],
+                    'raw_response' => $response['raw_response']
                 ];
             }
 
@@ -485,7 +490,8 @@ public function authorizeOrder($orderId)
                 'success' => false,
                 'error' => 'Failed to authorize order',
                 'status_code' => $response['body']['status'] ?? $response['status_code'],
-                'details' => $response['body']
+                'details' => $response['body'],
+                'raw_response' => $response['raw_response']
             ];
         } catch (\Exception $e) {
             return [
@@ -508,7 +514,8 @@ public function captureOrder($orderId)
                     'success' => true,
                     'capture_id' => $response['body']['purchase_units'][0]['payments']['captures'][0]['id'],
                     'status' => $response['body']['status'] ?? $response['status_code'],
-                    'full_response' => $response['body']
+                    'full_response' => $response['body'],
+                    'raw_response' => $response['raw_response']
                 ];
             }
 
@@ -516,7 +523,8 @@ public function captureOrder($orderId)
                 'success' => false,
                 'error' => 'Failed to capture order',
                 'status_code' => $response['body']['status'] ?? $response['status_code'],
-                'details' => $response['body']
+                'details' => $response['body'],
+                'raw_response' => $response['raw_response']
             ];
         } catch (\Exception $e) {
             return [
@@ -655,6 +663,359 @@ public function DoDirectPayment($paymentData) {
         return $responseSimplified;
     }
 
+    /**
+     * Creates a PayPal Order (REST API) equivalent to Classic SetExpressCheckout.
+     *
+     * Accepts Classic NVP-style array input ($DataArray), converts it
+     * into a PayPal REST /v2/checkout/orders payload, sends the create
+     * order request, and returns normalized NVP-compatible output.
+     */
+    function SetExpressCheckout($DataArray) {
+        $SECFields = isset($DataArray['SECFields']) ? $DataArray['SECFields'] : [];
+        $payments = isset($DataArray['Payments'][0]) ? $DataArray['Payments'][0] : [];
+        $items = isset($payments['order_items']) ? $payments['order_items'] : [];
+
+        $purchase_items = [];
+        $item_total = 0;
+
+        foreach ($items as $it) {
+            $purchase_items[] = array(
+                "name" => isset($it["name"]) ? $it["name"] : "",
+                "description" => isset($it["desc"]) ? $it["desc"] : "",
+                "quantity" => isset($it["qty"]) ? $it["qty"] : "1",
+                "unit_amount" => [
+                    "currency_code" => isset($payments["currencycode"]) ? $payments["currencycode"] : "USD",
+                    "value" => isset($it["amt"]) ? $it["amt"] : "0.00"
+                ],
+                "category" => !empty($it["itemcategory"]) && strtolower($it["itemcategory"]) === "digital"
+                    ? "DIGITAL_GOODS"
+                    : "PHYSICAL_GOODS"
+            );
+
+            $item_total += (float) (isset($it["amt"]) ? $it["amt"] : 0) * (int) (isset($it["qty"]) ? $it["qty"] : 1);
+        }
+
+        // Amount breakdown
+        $currency = isset($payments["currencycode"]) ? $payments["currencycode"] : "USD";
+
+        $amount = array(
+            "currency_code" => $currency,
+            "value" => isset($payments["amt"]) ? $payments["amt"] : "0.00",
+            "breakdown" => array(
+                "item_total" => array(
+                    "currency_code" => $currency,
+                    "value" => number_format($item_total, 2, '.', '')
+                ),
+                "shipping" => array(
+                    "currency_code" => $currency,
+                    "value" => isset($payments["shippingamt"]) ? $payments["shippingamt"] : "0.00"
+                ),
+                "tax_total" => array(
+                    "currency_code" => $currency,
+                    "value" => isset($payments["taxamt"]) ? $payments["taxamt"] : "0.00"
+                )
+            )
+        );
+
+        $payload = array(
+            "intent" => "CAPTURE",
+            "purchase_units" => array(
+                array(
+                    "amount" => $amount,
+                    "description" => isset($payments["desc"]) ? $payments["desc"] : "",
+                    "items" => $purchase_items
+                )
+            ),
+            "application_context" => array(
+                "return_url" => isset($SECFields["returnurl"]) ? $SECFields["returnurl"] : "",
+                "cancel_url" => isset($SECFields["cancelurl"]) ? $SECFields["cancelurl"] : "",
+                "brand_name" => isset($SECFields["brandname"]) ? $SECFields["brandname"] : "",
+                "landing_page" => strtoupper(isset($SECFields["landingpage"]) ? $SECFields["landingpage"] : "LOGIN"),
+                "shipping_preference" => (isset($SECFields["noshipping"]) && $SECFields["noshipping"] === "1")
+                    ? "NO_SHIPPING"
+                    : "SET_PROVIDED_ADDRESS"
+            )
+        );
+
+        $response = $this->createOrder($payload);
+
+        if ($this->api_upgrade && isset($response['success'])) {
+
+            $response['TOKEN'] = isset($response['order_id']) ? $response['order_id'] : '';
+            $response['REDIRECTURL'] = isset($response['approval_url']) ? $response['approval_url'] : '';
+            $response['ACK'] = 'Success';
+            $response['TIMESTAMP'] = gmdate('Y-m-d\TH:i:s\Z');
+            $response['RAWRESPONSE'] = isset($response['raw_response']) ? $response['raw_response'] : [];
+
+            // Cleanup for backward compatibility
+            unset(
+                $response['success'],
+                $response['order_id'],
+                $response['approval_url'],
+                $response['raw_response']
+            );
+        }
+
+        return $response;
+    }
+
+    /**
+     * Retrieves PayPal Order details (REST API) equivalent to Classic
+     * GetExpressCheckoutDetails. Converts REST order details into
+     * Classic NVP-compatible output.
+     *
+     * Required structure of $DataArray:
+     */
+    function GetExpressCheckoutDetails($DataArray) {
+        $orderId = isset($DataArray['DECPFields']['token']) ? $DataArray['DECPFields']['token'] : '';
+
+        $response = $this->getOrder($orderId);
+
+        if ($this->api_upgrade && isset($response['success'])) {
+            $responseData = array();
+
+            $responseData['TOKEN']  = isset($DataArray['DECPFields']['token']) ? $DataArray['DECPFields']['token'] : '';
+            $responseData['BILLINGAGREEMENTACCEPTEDSTATUS']  = false;
+            $responseData['NOTE']   = isset($DataArray['Payments'][0]['notetext']) ? $DataArray['Payments'][0]['notetext'] : '';
+            $responseData['CHECKOUTSTATUS'] = '';
+            $responseData['TIMESTAMP'] = gmdate('Y-m-d\TH:i:s\Z');
+            $responseData['CORRELATIONID'] = '';
+            $responseData['ACK'] = 'Success';
+
+            $responseData['PAYERID'] = isset($response['order']['payer']['payer_id']) ? $response['order']['payer']['payer_id'] : '';
+            $responseData['PAYERSTATUS'] = isset($response['order']['payment_source']['paypal']['account_status']) ? $response['order']['payment_source']['paypal']['account_status'] : '';
+            $responseData['EMAIL'] = isset($response['order']['payer']['email_address']) ? $response['order']['payer']['email_address'] : '';
+            $responseData['FIRSTNAME'] = isset($response['order']['payer']['name']['given_name']) ? $response['order']['payer']['name']['given_name'] : '';
+            $responseData['LASTNAME'] = isset($response['order']['payer']['name']['surname']) ? $response['order']['payer']['name']['surname'] : '';
+            $responseData['COUNTRYCODE'] = isset($response['order']['payer']['address']['country_code']) ? $response['order']['payer']['address']['country_code'] : '';
+
+            $responseData['DESC']   = isset($DataArray['Payments'][0]['desc']) ? $DataArray['Payments'][0]['desc'] : '';
+            $responseData['CURRENCYCODE'] = isset($DataArray['Payments'][0]['currencycode']) ? $DataArray['Payments'][0]['currencycode'] : '';
+            $responseData['AMT']    = isset($DataArray['Payments'][0]['amt']) ? $DataArray['Payments'][0]['amt'] : '0.00';
+            $responseData['ITEMAMT'] = isset($DataArray['Payments'][0]['itemamt']) ? $DataArray['Payments'][0]['itemamt'] : '0.00';
+            $responseData['SHIPPINGAMT'] = isset($DataArray['Payments'][0]['shippingamt']) ? $DataArray['Payments'][0]['shippingamt'] : '0.00';
+            $responseData['TAXAMT'] = isset($DataArray['Payments'][0]['taxamt']) ? $DataArray['Payments'][0]['taxamt'] : '0.00';
+            $responseData['HANDLINGAMT'] = isset($DataArray['Payments'][0]['handlingamt']) ? $DataArray['Payments'][0]['handlingamt'] : '0.00';
+
+            // PAYMENTREQUEST LEVEL
+            $payment = $DataArray['Payments'][0];
+
+            $responseData['PAYMENTREQUEST_0_AMT']          = isset($payment['amt']) ? $payment['amt'] : '0.00';
+            $responseData['PAYMENTREQUEST_0_CURRENCYCODE'] = isset($payment['currencycode']) ? $payment['currencycode'] : '';
+            $responseData['PAYMENTREQUEST_0_ITEMAMT']      = isset($payment['itemamt']) ? $payment['itemamt'] : '0.00';
+            $responseData['PAYMENTREQUEST_0_SHIPPINGAMT']  = isset($payment['shippingamt']) ? $payment['shippingamt'] : '0.00';
+            $responseData['PAYMENTREQUEST_0_TAXAMT']       = isset($payment['taxamt']) ? $payment['taxamt'] : '0.00';
+            $responseData['PAYMENTREQUEST_0_HANDLINGAMT']  = isset($payment['handlingamt']) ? $payment['handlingamt'] : '0.00';
+            $responseData['PAYMENTREQUEST_0_DESC']         = isset($payment['desc']) ? $payment['desc'] : '';
+            $responseData['PAYMENTREQUEST_0_NOTETEXT']     = isset($payment['notetext']) ? $payment['notetext'] : '';
+
+            // ORDER ITEMS
+            $items = isset($payment['order_items']) ? $payment['order_items'] : array();
+            $orderItemsArray = array();
+
+            foreach ($items as $i => $item) {
+
+                $responseData["L_NAME$i"]    = isset($item['name']) ? $item['name'] : '';
+                $responseData["L_DESC$i"]    = isset($item['desc']) ? $item['desc'] : '';
+                $responseData["L_NUMBER$i"]  = isset($item['number']) ? $item['number'] : '';
+                $responseData["L_QTY$i"]     = isset($item['qty']) ? $item['qty'] : '';
+                $responseData["L_AMT$i"]     = isset($item['amt']) ? $item['amt'] : '';
+                $responseData["L_TAXAMT$i"]  = isset($item['taxamt']) ? $item['taxamt'] : "0.00";
+
+                $responseData["L_PAYMENTREQUEST_0_NAME$i"]   = isset($item['name']) ? $item['name'] : '';
+                $responseData["L_PAYMENTREQUEST_0_DESC$i"]   = isset($item['desc']) ? $item['desc'] : '';
+                $responseData["L_PAYMENTREQUEST_0_NUMBER$i"] = isset($item['number']) ? $item['number'] : '';
+                $responseData["L_PAYMENTREQUEST_0_QTY$i"]    = isset($item['qty']) ? $item['qty'] : '';
+                $responseData["L_PAYMENTREQUEST_0_AMT$i"]    = isset($item['amt']) ? $item['amt'] : '';
+                $responseData["L_PAYMENTREQUEST_0_TAXAMT$i"] = isset($item['taxamt']) ? $item['taxamt'] : "0.00";
+
+                $orderItemsArray[$i] = array(
+                    'L_NAME'   => isset($item['name']) ? $item['name'] : '',
+                    'L_DESC'   => isset($item['desc']) ? $item['desc'] : '',
+                    'L_NUMBER' => isset($item['number']) ? $item['number'] : '',
+                    'L_QTY'    => isset($item['qty']) ? $item['qty'] : '',
+                    'L_AMT'    => isset($item['amt']) ? $item['amt'] : '',
+                    'L_OPTIONSNAME' => isset($item['optionsname']) ? $item['optionsname'] : '',
+                    'L_OPTIONSVALUE' => isset($item['optionsvalue']) ? $item['optionsvalue'] : '',
+                    'L_ITEMWEIGHTVALUE' => isset($item['itemweightvalue']) ? $item['itemweightvalue'] : '',
+                    'L_ITEMWEIGHTUNIT'  => isset($item['itemweightunit']) ? $item['itemweightunit'] : '',
+                    'L_ITEMWIDTHVALUE' => isset($item['itemwidthvalue']) ? $item['itemwidthvalue'] : '',
+                    'L_ITEMWIDTHUNIT'  => isset($item['itemwidthunit']) ? $item['itemwidthunit'] : '',
+                    'L_ITEMHEIGHTVALUE' => isset($item['itemheightvalue']) ? $item['itemheightvalue'] : '',
+                    'L_ITEMHEIGHTUNIT'  => isset($item['itemheightunit']) ? $item['itemheightunit'] : '',
+                    'L_ITEMLENGTHVALUE' => isset($item['itemlengthvalue']) ? $item['itemlengthvalue'] : '',
+                    'L_ITEMLENGTHUNIT'  => isset($item['itemlengthunit']) ? $item['itemlengthunit'] : '',
+                    'L_EBAYITEMNUMBER' => isset($item['ebayitemnumber']) ? $item['ebayitemnumber'] : '',
+                    'L_EBAYITEMAUCTIONTXNID' => isset($item['ebayitemauctiontxnid']) ? $item['ebayitemauctiontxnid'] : '',
+                    'L_EBAYITEMORDERID' => isset($item['ebayitemorderid']) ? $item['ebayitemorderid'] : '',
+                    'L_EBAYITEMCARTID' => isset($item['ebayitemcartid']) ? $item['ebayitemcartid'] : '',
+                    'L_TAXAMT' => isset($item['taxamt']) ? $item['taxamt'] : "0.00",
+                );
+            }
+
+            // PAYMENT REQUEST BLOCK FOR RESPONSE
+            $responseData['PAYMENTS'] = array();
+            $responseData['PAYMENTS'][0] = array(
+                'AMT'          => isset($payment['amt']) ? $payment['amt'] : '0.00',
+                'CURRENCYCODE' => isset($payment['currencycode']) ? $payment['currencycode'] : '',
+                'ITEMAMT'      => isset($payment['itemamt']) ? $payment['itemamt'] : '0.00',
+                'SHIPPINGAMT'  => isset($payment['shippingamt']) ? $payment['shippingamt'] : '0.00',
+                'TAXAMT'       => isset($payment['taxamt']) ? $payment['taxamt'] : '0.00',
+                'HANDLINGAMT'  => isset($payment['handlingamt']) ? $payment['handlingamt'] : '0.00',
+                'DESC'         => isset($payment['desc']) ? $payment['desc'] : '',
+                'NOTETEXT'     => isset($payment['notetext']) ? $payment['notetext'] : '',
+                'ORDERITEMS'   => array_map(
+                    function ($it) {
+                        return array(
+                            'NAME'  => isset($it['L_NAME']) ? $it['L_NAME'] : '',
+                            'DESC'  => isset($it['L_DESC']) ? $it['L_DESC'] : '',
+                            'AMT'   => isset($it['L_AMT']) ? $it['L_AMT'] : '',
+                            'NUMBER'=> isset($it['L_NUMBER']) ? $it['L_NUMBER'] : '',
+                            'QTY'   => isset($it['L_QTY']) ? $it['L_QTY'] : '',
+                            'TAXAMT'=> isset($it['L_TAXAMT']) ? $it['L_TAXAMT'] : '0.00',
+
+                            'OPTIONSNAME' => isset($it['L_OPTIONSNAME']) ? $it['L_OPTIONSNAME'] : '',
+                            'OPTIONSVALUE' => isset($it['L_OPTIONSVALUE']) ? $it['L_OPTIONSVALUE'] : '',
+
+                            'ITEMWEIGHTVALUE' => isset($it['L_ITEMWEIGHTVALUE']) ? $it['L_ITEMWEIGHTVALUE'] : '',
+                            'ITEMWEIGHTUNIT'  => isset($it['L_ITEMWEIGHTUNIT']) ? $it['L_ITEMWEIGHTUNIT'] : '',
+
+                            'ITEMWIDTHVALUE' => isset($it['L_ITEMWIDTHVALUE']) ? $it['L_ITEMWIDTHVALUE'] : '',
+                            'ITEMWIDTHUNIT'  => isset($it['L_ITEMWIDTHUNIT']) ? $it['L_ITEMWIDTHUNIT'] : '',
+
+                            'ITEMHEIGHTVALUE' => isset($it['L_ITEMHEIGHTVALUE']) ? $it['L_ITEMHEIGHTVALUE'] : '',
+                            'ITEMHEIGHTUNIT'  => isset($it['L_ITEMHEIGHTUNIT']) ? $it['L_ITEMHEIGHTUNIT'] : '',
+
+                            'ITEMLENGTHVALUE' => isset($it['L_ITEMLENGTHVALUE']) ? $it['L_ITEMLENGTHVALUE'] : '',
+                            'ITEMLENGTHUNIT'  => isset($it['L_ITEMLENGTHUNIT']) ? $it['L_ITEMLENGTHUNIT'] : '',
+
+                            'EBAYITEMNUMBER' => isset($it['L_EBAYITEMNUMBER']) ? $it['L_EBAYITEMNUMBER'] : '',
+                            'EBAYITEMAUCTIONTXNID' => isset($it['L_EBAYITEMAUCTIONTXNID']) ? $it['L_EBAYITEMAUCTIONTXNID'] : '',
+                            'EBAYITEMORDERID' => isset($it['L_EBAYITEMORDERID']) ? $it['L_EBAYITEMORDERID'] : '',
+                            'EBAYITEMCARTID' => isset($it['L_EBAYITEMCARTID']) ? $it['L_EBAYITEMCARTID'] : '',
+                        );
+                    },
+                    $orderItemsArray
+                )
+            );
+
+            $responseData['FULLRESPONSE'] = isset($response['order']) ? $response['order'] : array();
+            $responseData['RAWRESPONSE'] = isset($response['raw_response']) ? $response['raw_response'] : array();
+        }
+
+        return $this->api_upgrade ? $responseData : $response;
+    }
+
+    /**
+     * Captures a PayPal Order (REST API) equivalent to Classic
+     * DoExpressCheckoutPayment. Converts REST capture response
+     * into Classic PayPal NVP-compatible structure.
+     */
+    function DoExpressCheckoutPayment($DataArray) {
+        $orderId = isset($DataArray['DECPFields']['token']) ? $DataArray['DECPFields']['token'] : '';
+
+        $response = $this->captureOrder($orderId);
+
+        if ($this->api_upgrade && isset($response['success'])) {
+            $responseData = array();
+
+            $responseData['TOKEN']  = isset($response['capture_id']) ? $response['capture_id'] : '';
+            $responseData['BILLINGAGREEMENTACCEPTEDSTATUS']  = false;
+            $responseData['NOTE']   = isset($DataArray['Payments'][0]['notetext']) ? $DataArray['Payments'][0]['notetext'] : '';
+            $responseData['CHECKOUTSTATUS'] = '';
+            $responseData['TIMESTAMP'] = gmdate('Y-m-d\TH:i:s\Z');
+            $responseData['CORRELATIONID'] = '';
+            $responseData['ACK'] = 'Success';
+            $responseData['INSURANCEOPTIONSELECTED'] = 'false';
+            $responseData['SHIPPINGOPTIONISDEFAULT'] = 'false';
+
+            $fullResponse  = isset($response['full_response']) ? $response['full_response'] : array();
+            $payer = isset($fullResponse['payer']) ? $fullResponse['payer'] : array();
+
+            $unit  = isset($fullResponse['purchase_units'][0]) ? $fullResponse['purchase_units'][0] : array();
+
+            $capture = array();
+            if (isset($unit['payments']['captures'][0])) {
+                $capture = $unit['payments']['captures'][0];
+            }
+
+            // Amounts
+            $amount   = isset($capture['amount']['value']) ? $capture['amount']['value'] : '';
+            $currency = isset($capture['amount']['currency_code']) ? $capture['amount']['currency_code'] : '';
+
+            $fee = isset($capture['seller_receivable_breakdown']['paypal_fee']['value']) 
+                    ? $capture['seller_receivable_breakdown']['paypal_fee']['value'] 
+                    : '';
+
+            $gross = isset($capture['seller_receivable_breakdown']['gross_amount']['value']) 
+                    ? $capture['seller_receivable_breakdown']['gross_amount']['value'] 
+                    : '';
+
+            $net = isset($capture['seller_receivable_breakdown']['net_amount']['value']) 
+                ? $capture['seller_receivable_breakdown']['net_amount']['value'] 
+                : '';
+
+            // Tax not provided in REST
+            $tax = '';
+
+            // Protection categories
+            $protectionTypes = '';
+            if (isset($capture['seller_protection']['dispute_categories']) 
+                && is_array($capture['seller_protection']['dispute_categories'])) {
+
+                $protectionTypes = implode(',', $capture['seller_protection']['dispute_categories']);
+            }
+
+            // Build NVP output
+            $responseData = array(
+                "PAYMENTINFO_0_TRANSACTIONID"           => isset($capture['id']) ? $capture['id'] : '',
+                "PAYMENTINFO_0_TRANSACTIONTYPE"         => "cart",
+                "PAYMENTINFO_0_PAYMENTTYPE"             => "instant",
+                "PAYMENTINFO_0_ORDERTIME"               => isset($capture['create_time']) ? $capture['create_time'] : '',
+                "PAYMENTINFO_0_AMT"                     => $amount,
+                "PAYMENTINFO_0_FEEAMT"                  => $fee,
+                "PAYMENTINFO_0_TAXAMT"                  => $tax,
+                "PAYMENTINFO_0_CURRENCYCODE"            => $currency,
+                "PAYMENTINFO_0_PAYMENTSTATUS"           => isset($capture['status']) ? ucfirst(strtolower($capture['status'])) : '',
+                "PAYMENTINFO_0_PENDINGREASON"           => "None",
+                "PAYMENTINFO_0_REASONCODE"              => "None",
+                "PAYMENTINFO_0_PROTECTIONELIGIBILITY"   => isset($capture['seller_protection']['status']) ? $capture['seller_protection']['status'] : '',
+                "PAYMENTINFO_0_PROTECTIONELIGIBILITYTYPE" => $protectionTypes,
+                "PAYMENTINFO_0_SELLERPAYPALACCOUNTID"   => "",
+                "PAYMENTINFO_0_SECUREMERCHANTACCOUNTID" => "",
+                "PAYMENTINFO_0_ERRORCODE"               => 0,
+                "PAYMENTINFO_0_ACK"                     => "Success",
+                "ERRORS"                                => array(),
+                "PAYMENTS"                              => array(
+                    array(
+                        "TRANSACTIONID"      => isset($capture['id']) ? $capture['id'] : '',
+                        "TRANSACTIONTYPE"    => "cart",
+                        "PAYMENTTYPE"        => "instant",
+                        "ORDERTIME"          => isset($capture['create_time']) ? $capture['create_time'] : '',
+                        "AMT"                => $amount,
+                        "FEEAMT"             => $fee,
+                        "SETTLEAMT"          => "",
+                        "TAXAMT"             => $tax,
+                        "EXCHANGERATE"       => "",
+                        "CURRENCYCODE"       => $currency,
+                        "PAYMENTSTATUS"      => isset($capture['status']) ? ucfirst(strtolower($capture['status'])) : '',
+                        "PENDINGREASON"      => "None",
+                        "REASONCODE"         => "None",
+                        "PROTECTIONELIGIBILITY" => isset($capture['seller_protection']['status']) ? $capture['seller_protection']['status'] : '',
+                        "ERRORCODE"          => 0,
+                        "FMFILTERS"          => array(),
+                        "ERRORS"             => array()
+                    )
+                )
+            );
+
+            $responseData['FULLRESPONSE'] = isset($response['full_response']) ? $response['full_response'] : array();
+            $responseData['RAWRESPONSE'] = isset($response['raw_response']) ? $response['raw_response'] : array();
+        }
+
+        return $this->api_upgrade ? $responseData : $response;
+    }
+
     /**
      * Create a recurring payments profile using PayPal REST APIs.
      *

From 3b9e00ce14f7b2485dd32eda27e83cb369cf91a8 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 24 Nov 2025 20:36:21 +0530
Subject: [PATCH 033/146] Conversion of GetPalDetails Completed

---
 samples/sample-methods/GetPalDetails.php | 28 ++++++++++++++++++++++++
 src/angelleye/PayPal/PayPalREST.php      | 13 ++++++++++-
 2 files changed, 40 insertions(+), 1 deletion(-)
 create mode 100644 samples/sample-methods/GetPalDetails.php

diff --git a/samples/sample-methods/GetPalDetails.php b/samples/sample-methods/GetPalDetails.php
new file mode 100644
index 00000000..8c389dbb
--- /dev/null
+++ b/samples/sample-methods/GetPalDetails.php
@@ -0,0 +1,28 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+    'PayPalAPIUpgrade' => $api_upgrade,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetPalDetails();
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 06a2ff72..8dad187a 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1310,7 +1310,18 @@ public function GetPalDetails() {
         try {
             $response = $this->makeRequest('/v1/identity/oauth2/userinfo?schema=paypalv1.1');
 
-            if ($response['status_code'] === 201) {
+            if (in_array($response['status_code'], [200, 201])) {
+
+                if ($this->api_upgrade) {
+                    return [
+                        'PAL' => isset($response['body']['payer_id']) ? $response['body']['payer_id'] : '',
+                        'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
+                        'ACK' => 'Success',
+                        'full_response' => $response['body'],
+                        'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                    ];
+                }
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],

From 383a98eba8a09e415b37bebfcd76aac89230ccf6 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 24 Nov 2025 20:38:04 +0530
Subject: [PATCH 034/146] Conversion of GetPaymentOptions Completed

---
 samples/sample-methods/GetPaymentOptions.php | 40 ++++++++++++++++++++
 1 file changed, 40 insertions(+)
 create mode 100644 samples/sample-methods/GetPaymentOptions.php

diff --git a/samples/sample-methods/GetPaymentOptions.php b/samples/sample-methods/GetPaymentOptions.php
new file mode 100644
index 00000000..458f7c9a
--- /dev/null
+++ b/samples/sample-methods/GetPaymentOptions.php
@@ -0,0 +1,40 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayKey = 'AP-8GH334440A259981L';
+if( $api_mode === 'rest' ){
+	$PayPalResult = $PayPal->getOrder($PayKey);
+	echo '
';
+} else {
+	$PayPalResult = $PayPal->Adaptive->GetPaymentOptions($PayKey);
+	echo '
';
+	echo "

Deprecated Notice: The classic CreateInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); \ No newline at end of file From 254e62862ec38d165075011123aa4575a18decf7 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 24 Nov 2025 20:40:02 +0530 Subject: [PATCH 035/146] Conversion of CreateRecurringPaymentsProfile Completed --- .../CreateRecurringPaymentsProfile.php | 143 ++++++++++++++++++ src/angelleye/PayPal/PayPalREST.php | 83 ++++++++++ 2 files changed, 226 insertions(+) create mode 100644 samples/sample-methods/CreateRecurringPaymentsProfile.php diff --git a/samples/sample-methods/CreateRecurringPaymentsProfile.php b/samples/sample-methods/CreateRecurringPaymentsProfile.php new file mode 100644 index 00000000..81046df4 --- /dev/null +++ b/samples/sample-methods/CreateRecurringPaymentsProfile.php @@ -0,0 +1,143 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$CRPPFields = array( + 'token' => 'EC-2A900424LS312982Y', // Token returned from PayPal SetExpressCheckout. Can also use token returned from SetCustomerBillingAgreement. +); + +$DaysTimestamp = strtotime('now'); +$Mo = date('m', $DaysTimestamp); +$Day = date('d', $DaysTimestamp); +$Year = date('Y', $DaysTimestamp); +$StartDateGMT = $Year . '-' . $Mo . '-' . $Day . 'T00:00:00\Z'; + +$ProfileDetails = array( + 'subscribername' => 'Tester Testerson', // Full name of the person receiving the product or service paid for by the recurring payment. 32 char max. + 'profilestartdate' => $StartDateGMT, // Required. The date when the billing for this profile begins. Must be a valid date in UTC/GMT format. + 'profilereference' => '' // The merchant's own unique invoice number or reference ID. 127 char max. +); + +$ScheduleDetails = array( + 'desc' => 'Angell EYE Web Hosting', // Required. Description of the recurring payment. This field must match the corresponding billing agreement description included in SetExpressCheckout. + 'maxfailedpayments' => '', // The number of scheduled payment periods that can fail before the profile is automatically suspended. + 'autobillamt' => '1' // This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle. Values can be: NoAutoBill or AddToNextBilling +); + +$BillingPeriod = array( + 'trialbillingperiod' => '', + 'trialbillingfrequency' => '', + 'trialtotalbillingcycles' => '', + 'trialamt' => '', + 'billingperiod' => 'Day', // Required. Unit for billing during this subscription period. One of the following: Day, Week, SemiMonth, Month, Year + 'billingfrequency' => '1', // Required. Number of billing periods that make up one billing cycle. The combination of billing freq. and billing period must be less than or equal to one year. + 'totalbillingcycles' => '0', // the number of billing cycles for the payment period (regular or trial). For trial period it must be greater than 0. For regular payments 0 means indefinite...until canceled. + 'amt' => '10.00', // Required. Billing amount for each billing cycle during the payment period. This does not include shipping and tax. + 'currencycode' => 'USD', // Required. Three-letter currency code. + 'shippingamt' => '', // Shipping amount for each billing cycle during the payment period. + 'taxamt' => '' // Tax amount for each billing cycle during the payment period. +); + +$ActivationDetails = array( + 'initamt' => '', // Initial non-recurring payment amount due immediatly upon profile creation. Use an initial amount for enrolment or set-up fees. + 'failedinitamtaction' => '', // By default, PayPal will suspend the pending profile in the event that the initial payment fails. You can override this. Values are: ContinueOnFailure or CancelOnFailure +); + +$CCDetails = array( + 'creditcardtype' => 'Visa', // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. + 'acct' => '4635800000971893', // Required. Credit card number. No spaces or punctuation. + 'expdate' => '022019', // Required. Credit card expiration date. Format is MMYYYY + 'cvv2' => '123', // Requirements determined by your PayPal account settings. Security digits for credit card. + 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY + 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. +); + +$PayerInfo = array( + 'email' => 'tester@hey.com', // Email address of payer. + 'payerid' => '', // Unique PayPal customer ID for payer. + 'payerstatus' => '', // Status of payer. Values are verified or unverified + 'countrycode' => '', // Payer's country of residence in the form of the two letter code. + 'business' => 'Testers, LLC' // Payer's business name. +); + +$PayerName = array( + 'salutation' => '', // Payer's salutation. 20 char max. + 'firstname' => 'Tester', // Payer's first name. 25 char max. + 'middlename' => '', // Payer's middle name. 25 char max. + 'lastname' => 'Testerson', // Payer's last name. 25 char max. + 'suffix' => '' // Payer's suffix. 12 char max. +); + +$BillingAddress = array( + 'street' => '123 Test Ave.', // Required. First street address. + 'street2' => '', // Second street address. + 'city' => 'Grandview', // Required. Name of City. + 'state' => 'MO', // Required. Name of State or Province. + 'countrycode' => 'US', // Required. Country code. + 'zip' => '64030', // Required. Postal code of payer. + 'phonenum' => '' // Phone Number of payer. 20 char max. +); + +$ShippingAddress = array( + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountrycode' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '' // Phone number for shipping address. 20 char max. +); + +$PayPalRequestData = array( + 'ProfileDetails' => $ProfileDetails, + 'ScheduleDetails' => $ScheduleDetails, + 'BillingPeriod' => $BillingPeriod, + 'CCDetails' => $CCDetails, + 'PayerInfo' => $PayerInfo, + 'PayerName' => $PayerName, + 'BillingAddress' => $BillingAddress +); +if( $api_mode == 'rest' ) { + $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($domain); + + if ($PayPalResult['success']) { + $approve_url = ''; + if (!empty($PayPalResult['response']['links'])) { + foreach ($PayPalResult['response']['links'] as $link) { + if (isset($link['rel']) && $link['rel'] === 'approve') { + $approve_url = $link['href']; + break; + } + } + } + echo 'Click here to continue.

'; + + echo '
';
+        print_r($PayPalResult);
+    }
+} else {
+    $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($PayPalRequestData);
+
+    echo '
';
+    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + print_r($PayPalResult); + +} + diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php index 8dad187a..37ad9400 100644 --- a/src/angelleye/PayPal/PayPalREST.php +++ b/src/angelleye/PayPal/PayPalREST.php @@ -1343,6 +1343,89 @@ public function GetPalDetails() { } } + /** + * Creates a sample recurring payments profile with predefined data. + * + * This method sets up a sample product, billing plan, and subscription + * for demonstration purposes. It uses hardcoded values for the product name, + * plan details, and subscriber information. + */ + public function CreateRecurringPaymentsProfile( $domain ){ + + $ProductData = array( + "name" => "Angell EYE Web Hosting", + "description" => "Web hosting recurring subscription", + "type" => "SERVICE", + "category" => "SOFTWARE", + ); + + $PlanData = array( + "product_id" => '', + "name" => "Daily Hosting Plan", + "description" => "Daily recurring billing for hosting", + "billing_cycles" => array( + array( + "frequency" => array( + "interval_unit" => "DAY", + "interval_count" => 1 + ), + "tenure_type" => "REGULAR", + "sequence" => 1, + "total_cycles" => 0, // 0 = infinite + "pricing_scheme" => array( + "fixed_price" => array( + "value" => "10.00", + "currency_code" => "USD" + ) + ) + ) + ), + "payment_preferences" => array( + "auto_bill_outstanding" => true, + "setup_fee_failure_action" => "CONTINUE", + "payment_failure_threshold" => 3 + ) + ); + + $SubscriptionData = array( + "plan_id" => '', + "start_time" => gmdate("Y-m-d\TH:i:s\Z", strtotime("+10 minutes")), + "subscriber" => array( + "name" => array( + "given_name" => "Tester", + "surname" => "Testerson" + ), + "email_address" => "tester@hey.com", + "shipping_address" => array( + "name" => array("full_name" => "Tester Testerson"), + "address" => array( + "address_line_1" => "123 Test Ave.", + "admin_area_2" => "Grandview", + "admin_area_1" => "MO", + "postal_code" => "64030", + "country_code" => "US" + ) + ) + ), + "application_context" => array( + "brand_name" => "Angell EYE Web Hosting", + "locale" => "en-US", + "shipping_preference" => "SET_PROVIDED_ADDRESS", + "user_action" => "SUBSCRIBE_NOW", + 'return_url' => $domain . 'samples/rest/GetRecurringPaymentsProfileDetails.php', + 'cancel_url' => $domain . 'samples/rest/', + ) + ); + + $PayPalRequestData = array( + 'ProductData' => $ProductData, + 'PlanData' => $PlanData, + 'SubscriptionData' => $SubscriptionData, + ); + + return $this->CreateSubscriptionProfile($PayPalRequestData); + } + /** * Retrieves user information using the PayPal REST Identity API. * From 084c6f81c7d73f01f14c986541a50c2df2a00de1 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 24 Nov 2025 20:42:35 +0530 Subject: [PATCH 036/146] Conversion of GetRecurringPaymentsProfileDetails Completed --- .../GetRecurringPaymentsProfileDetails.php | 44 ++++++++++++ src/angelleye/PayPal/PayPalREST.php | 68 ++++++++++++++++++- 2 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 samples/sample-methods/GetRecurringPaymentsProfileDetails.php diff --git a/samples/sample-methods/GetRecurringPaymentsProfileDetails.php b/samples/sample-methods/GetRecurringPaymentsProfileDetails.php new file mode 100644 index 00000000..564f858b --- /dev/null +++ b/samples/sample-methods/GetRecurringPaymentsProfileDetails.php @@ -0,0 +1,44 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +if( $api_mode === 'classic' ) { + // Prepare request arrays + $GRPPDFields = array( + 'profileid' => 'I-W67GUR0BDTG6' // Profile ID of the profile you want to get details for. + ); + + $PayPalRequestData = array('GRPPDFields'=>$GRPPDFields); +} else{ + $PayPalRequestData = array( + 'token' => isset($_GET['token']) ? $_GET['token'] : '', + 'ba_token' => isset($_GET['ba_token']) ? $_GET['ba_token'] : '', + 'subscription_id' => isset($_GET['subscription_id']) ? $_GET['subscription_id'] : '', + ); +} + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$PayPalResult = $PayPal->GetRecurringPaymentsProfileDetails($PayPalRequestData); + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 37ad9400..67f1fe98 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1102,7 +1102,62 @@ public function GetSubscriptionProfile($DataArray) {
 
             $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId, 'GET');
 
-            if ($response['status_code'] === 201) {
+            if (in_array($response['status_code'], [200, 201])) {
+
+                if( $this->api_upgrade ) {
+
+                    $fullResponse = $response['body'];
+                    if( !empty( $fullResponse['subscriptions'] ) ){
+                        foreach( $fullResponse['subscriptions'] as $key => $value ){
+                            $subscriptionRes = $this->makeRequest('/v1/billing/subscriptions/' . $value['id'], 'GET');
+
+                            $giventName = ! empty( $subscriptionRes['body']['subscriber']['name']['given_name'] ) ? $subscriptionRes['body']['subscriber']['name']['given_name'] : '';
+                            $surname = ! empty( $subscriptionRes['body']['subscriber']['name']['surname'] ) ? $subscriptionRes['body']['subscriber']['name']['surname'] : '';
+                            $subscriberName = !empty( $giventName ) ? $giventName . ' ' . $surname : $surname;
+
+                            $responseData = array(
+                                'TIMESTAMP'             => ! empty( $subscriptionRes['body']['update_time'] ) ? $subscriptionRes['body']['update_time'] : gmdate('c'),
+                                'ACK'                   => !empty( $subscriptionRes['status_code'] ) && \in_array($subscriptionRes['status_code'],['200','201']) ? 'Success' : 'Failure',
+                                'STATUS'                => ! empty( $subscriptionRes['body']['status'] ) ? $subscriptionRes['body']['status'] : '-', 
+                                'PROFILEID'             => ! empty( $subscriptionRes['body']['id'] ) ? $subscriptionRes['body']['id'] : '-',
+                                'DESC'                  => ! empty( $subscriptionRes['body']['status_change_note'] ) ? $subscriptionRes['body']['status_change_note'] : '',
+                                'SUBSCRIBERNAME'        => $subscriberName,
+                                'PROFILESTARTDATE'      => ! empty( $subscriptionRes['body']['start_time'] ) ? $subscriptionRes['body']['start_time'] : '',
+                                'NEXTBILLINGDATE'       => ! empty( $subscriptionRes['body']['billing_info']['next_billing_time'] ) ? $subscriptionRes['body']['billing_info']['next_billing_time'] : '',
+                                'NUMCYCLESCOMPLETED'    => ! empty( $subscriptionRes['body']['billing_info']['cycle_executions'][0]['cycles_completed'] ) ? $subscriptionRes['body']['billing_info']['cycle_executions'][0]['cycles_completed'] : '',
+                                'NUMCYCLESREMAINING'    => ! empty( $subscriptionRes['body']['billing_info']['cycle_executions'][0]['cycles_remaining'] ) ? $subscriptionRes['body']['billing_info']['cycle_executions'][0]['cycles_remaining'] : '',
+                                'OUTSTANDINGBALANCE'    => ! empty( $subscriptionRes['body']['billing_info']['outstanding_balance']['value'] ) ? $subscriptionRes['body']['billing_info']['outstanding_balance']['value'] : '',
+                                'FAILEDPAYMENTCOUNT'    => ! empty( $subscriptionRes['body']['billing_info']['failed_payments_count'] ) ? $subscriptionRes['body']['billing_info']['failed_payments_count'] : '',
+                                'LASTPAYMENTDATE'       => ! empty( $subscriptionRes['body']['billing_info']['last_payment']['time'] ) ? $subscriptionRes['body']['billing_info']['last_payment']['time'] : '',
+                                'LASTPAYMENTAMT'        => ! empty( $subscriptionRes['body']['billing_info']['last_payment']['amount']['value'] ) ? $subscriptionRes['body']['billing_info']['last_payment']['amount']['value'] : '',
+                                'SHIPTONAME'            => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['name']['full_name'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['name']['full_name'] : '',
+                                'SHIPTOSTREET'          => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['address']['address_line_1'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['address']['address_line_1'] : '',
+                                'SHIPTOCITY'            => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['address']['admin_area_2'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['address']['admin_area_2'] : '',
+                                'SHIPTOSTATE'           => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['address']['admin_area_1'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['address']['admin_area_1'] : '',
+                                'SHIPTOZIP'             => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['address']['postal_code'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['address']['postal_code'] : '',
+                                'SHIPTOCOUNTRYCODE'     => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['address']['country_code'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['address']['country_code'] : '',
+                                'SHIPTOCOUNTRY'         => ! empty( $subscriptionRes['body']['subscriber']['shipping_address']['address']['country_code'] ) ? $subscriptionRes['body']['subscriber']['shipping_address']['address']['country_code'] : '',
+                                'SHIPADDRESSOWNER'      => ! empty( $subscriptionRes['body']['subscriber']['tenant'] ) ? $subscriptionRes['body']['subscriber']['tenant'] : '',
+                                'CURRENCYCODE'          => ! empty( $subscriptionRes['body']['billing_info']['last_payment']['amount']['currency_code'] ) ? $subscriptionRes['body']['billing_info']['last_payment']['amount']['currency_code'] : '',
+                                'AMT'                   => ! empty( $subscriptionRes['body']['billing_info']['last_payment']['amount']['value'] ) ? $subscriptionRes['body']['billing_info']['last_payment']['amount']['value'] : '', 
+                                'REGULARAMT'            => ! empty( $subscriptionRes['body']['billing_info']['last_payment']['amount']['value'] ) ? $subscriptionRes['body']['billing_info']['last_payment']['amount']['value'] : '',
+                                'SUBSCRIBEREMAIL'       => ! empty( $subscriptionRes['body']['subscriber']['email_address'] ) ? $subscriptionRes['body']['subscriber']['email_address'] : '',
+                                'FULLRESPONSE'          => ! empty( $subscriptionRes['body'] ) ? $subscriptionRes['body'] : [],
+                                'RAWRESPONSE'           => ! empty( $subscriptionRes['raw_response'] ) ? $subscriptionRes['raw_response'] : [],
+                            );
+
+                            $fullResponse['subscriptions'][$key] = $responseData;
+                        }
+                    }
+
+                    return [
+                        'success' => true,
+                        'subscription_id' => isset($response['body']['id']) ? $response['body']['id'] : '',
+                        'status' => $response['body']['status'] ?? $response['status_code'],
+                        'full_response' => $fullResponse
+                    ];
+                }
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1426,6 +1481,17 @@ public function CreateRecurringPaymentsProfile( $domain ){
         return $this->CreateSubscriptionProfile($PayPalRequestData);
     }
 
+    /**
+     * Retrieves details of a recurring payments profile using the provided request data.
+     *
+     * This method serves as a wrapper for the `GetSubscriptionProfile` function,
+     * allowing users to fetch information about a specific recurring payments profile
+     * based on the input parameters.
+     */
+    public function GetRecurringPaymentsProfileDetails( $PayPalRequestData ){
+        return $this->GetSubscriptionProfile($PayPalRequestData);
+    }
+
     /**
      * Retrieves user information using the PayPal REST Identity API.
      *

From 2a3c474deb91d7866445b05a974ccd06d402d4b1 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 24 Nov 2025 20:53:50 +0530
Subject: [PATCH 037/146] Conversion of ManageSubscriptionProfile Completed

---
 .../ManageRecurringPaymentsProfileStatus.php  | 50 +++++++++++++++++++
 src/angelleye/PayPal/PayPalREST.php           | 25 +++++++++-
 2 files changed, 74 insertions(+), 1 deletion(-)
 create mode 100644 samples/sample-methods/ManageRecurringPaymentsProfileStatus.php

diff --git a/samples/sample-methods/ManageRecurringPaymentsProfileStatus.php b/samples/sample-methods/ManageRecurringPaymentsProfileStatus.php
new file mode 100644
index 00000000..5b24263c
--- /dev/null
+++ b/samples/sample-methods/ManageRecurringPaymentsProfileStatus.php
@@ -0,0 +1,50 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+	'PayPalAPIUpgrade' => $api_upgrade,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+
+if($api_mode === 'rest'){
+	$PayPalRequestData = array(
+			'subscription_id' => 'I-FH010XMYUTPD',
+			'subscription_action' => 'cancel',                      // Action to be performed on the subscription.  Must be: cancel, suspend, activate
+			'subscription_reason' => 'Canceling the subscription profile.'          // Reason for the change in status
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->ManageRecurringPaymentsProfileStatus($PayPalRequestData);
+
+} else {
+	// Prepare request arrays
+	$MRPPSFields = array(
+		'profileid' => 'I-W67GUR0BDTG6', 		// Required. Recurring payments profile ID returned from CreateRecurring...
+		'action' => 'Reactivate', 			// Required. The action to be performed.  Mest be: Cancel, Suspend, Reactivate
+		'note' => ''					// The reason for the change in status.  For express checkout the message will be included in email to buyers.  Can also be seen in both accounts in the status history.
+	);
+						
+	$PayPalRequestData = array('MRPPSFields'=>$MRPPSFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->ManageRecurringPaymentsProfileStatus($PayPalRequestData);	
+}
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 67f1fe98..d8586d56 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1193,7 +1193,20 @@ public function ManageSubscriptionProfile($DataArray) {
 
             $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId . '/' . $subscriptionAction, 'POST', $subscriptionReason);
 
-            if ($response['status_code'] === 201) {
+            if ( $response['status_code'] >= 200 && $response['status_code'] < 300 ) {
+
+                if ($this->api_upgrade) {
+                    return [
+                        'success' => true,
+                        'status' => $response['body']['status'] ?? $response['status_code'],
+                        'ACK' => 'Success',
+                        'TIMESTAMP' => gmdate('c'),
+                        'PROFILEID' => isset($subscriptionId) ? $subscriptionId : '',
+                        'L_LONGMESSAGE0' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
+                        'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
+                    ];
+                }
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1492,6 +1505,16 @@ public function GetRecurringPaymentsProfileDetails( $PayPalRequestData ){
         return $this->GetSubscriptionProfile($PayPalRequestData);
     }
 
+    /**
+     * Manage recurring payments profile status by delegating to ManageSubscriptionProfile.
+     *
+     * This function is a wrapper that calls the ManageSubscriptionProfile method
+     * to perform actions such as canceling, suspending, or activating a subscription.
+     */
+    public function ManageRecurringPaymentsProfileStatus($DataArray) {
+        return $this->ManageSubscriptionProfile($DataArray);
+    }
+
     /**
      * Retrieves user information using the PayPal REST Identity API.
      *

From 5709f861dea81d47061fc60056339aac736648c5 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 24 Nov 2025 20:56:21 +0530
Subject: [PATCH 038/146] Conversion of CreateInvoice Completed

---
 samples/sample-methods/CreateInvoice.php | 236 +++++++++++++++++++++++
 1 file changed, 236 insertions(+)
 create mode 100644 samples/sample-methods/CreateInvoice.php

diff --git a/samples/sample-methods/CreateInvoice.php b/samples/sample-methods/CreateInvoice.php
new file mode 100644
index 00000000..118f9984
--- /dev/null
+++ b/samples/sample-methods/CreateInvoice.php
@@ -0,0 +1,236 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+        'PayPalAPIUpgrade' => $api_upgrade,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+if( $api_mode === 'classic' ){
+
+        // Prepare request arrays
+        $CreateInvoiceFields = array(
+                'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 				// Required.  Merchant email address.
+                'PayerEmail' => 'sandbo_1204199080_biz@angelleye.com', 					// Required.  Payer email address.
+                'Number' => '', 									// Unique ID for the invoice.
+                'CurrencyCode' => 'USD', 								// Required.  Currency used for all invoice item amounts and totals.
+                'InvoiceDate' => '', 									// Date on which the invoice is enabled.
+                'DueDate' => '', 									// Date on which the invoice payment is due.
+                'PaymentTerms' => 'DueOnReceipt', 							// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+                'DiscountPercent' => '', 								// Discount percent applied to the invoice.
+                'DiscountAmount' => '', 								// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+                'Terms' => '', 										// General terms for the invoice.
+                'Note' => 'This is a test invoice.', 							// Note to the payer company.
+                'MerchantMemo' => 'This is a test invoice.', 						// Memo for bookkeeping that is private to the merchant.
+                'ShippingAmount' => '10.00', 								// Cost of shipping
+                'ShippingTaxName' => '', 								// Name of the applicable tax on the shipping cost.
+                'ShippingTaxRate' => '', 								// Rate of the applicable tax on the shipping cost.
+                'LogoURL' => 'https://www.usbswiper.com/images/angelley-clients/cpp-header-image.jpg'	// Complete URL to an external image used as the logo, if any.
+        );
+                                                                
+        $BusinessInfo = array(
+                'FirstName' => 'Tester', 			// First name of the company contact.
+                'LastName' => 'Testerson', 			// Last name of the company contact.
+                'BusinessName' => 'Testers, LLC', 		// Company business name.
+                'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+                'Fax' => '555-555-5556', 			// Fax number used by the company.
+                'Website' => 'http://www.domain.com', 		// Website used by the company.
+                'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $BusinessInfoAddress = array(
+                'Line1' => '123 Main St.', 			// Required. First line of address.
+                'Line2' => '', 					// Second line of address.
+                'City' => 'Grandview', 				// Required. City of the address.
+                'State' => 'MO', 				// State for the address.
+                'PostalCode' => '64030', 			// Postal code of the address
+                'CountryCode' => 'US'				// Required.  Country code of the address.
+        );
+
+        $BillingInfo = array(
+                'FirstName' => 'Tester', 			// First name of the company contact.
+                'LastName' => 'Testerson', 			// Last name of the company contact.
+                'BusinessName' => 'Testers, LLC', 		// Company business name.
+                'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+                'Fax' => '555-555-5556', 			// Fax number used by the company.
+                'Website' => 'http://www.domain.com', 		// Website used by the company.
+                'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $BillingInfoAddress = array(
+                'Line1' => '123 Main St.', 			// Required. First line of address.
+                'Line2' => '', 					// Second line of address.
+                'City' => 'Grandview', 				// Required. City of the address.
+                'State' => 'MO', 				// State for the address.
+                'PostalCode' => '64030', 			// Postal code of the address
+                'CountryCode' => 'US'				// Required.  Country code of the address.
+        );
+
+        $ShippingInfo = array(
+                'FirstName' => 'Tester', 			// First name of the company contact.
+                'LastName' => 'Testerson', 			// Last name of the company contact.
+                'BusinessName' => 'Testers, LLC', 		// Company business name.
+                'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+                'Fax' => '555-555-5556', 			// Fax number used by the company.
+                'Website' => 'http://www.domain.com', 		// Website used by the company.
+                'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $ShippingInfoAddress = array(
+                'Line1' => '123 Main St.', 		// Required. First line of address.
+                'Line2' => '', 				// Second line of address.
+                'City' => 'Grandview', 			// Required. City of the address.
+                'State' => 'MO', 			// State for the address.
+                'PostalCode' => '64030', 		// Postal code of the address
+                'CountryCode' => 'US'			// Required.  Country code of the address.
+        );
+
+        // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
+        // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
+
+        $InvoiceItems = array();
+
+        $InvoiceItem = array(
+                'Name' => 'Test Widget 1', 				// Required.  SKU or name of the item.
+                'Description' => 'This is a test widget #1', 		// Item description.
+                'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+                'Quantity' => '1', 					// Required.  Item count.  Values are:  0 to 10000
+                'UnitPrice' => '10.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+                'TaxName' => '', 					// Name of the applicable tax.
+                'TaxRate' => ''						// Rate of the applicable tax.
+        );
+        array_push($InvoiceItems,$InvoiceItem);
+
+        $InvoiceItem = array(
+                'Name' => 'Test Widget 2', 				// Required.  SKU or name of the item.
+                'Description' => 'This is a test widget #2', 		// Item description.
+                'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+                'Quantity' => '2', 					// Required.  Item count.  Values are:  0 to 10000
+                'UnitPrice' => '20.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+                'TaxName' => '', 					// Name of the applicable tax.
+                'TaxRate' => ''						// Rate of the applicable tax.
+        );
+        array_push($InvoiceItems,$InvoiceItem);
+
+        $PayPalRequestData = array(
+                'CreateInvoiceFields' => $CreateInvoiceFields, 
+                'BusinessInfo' => $BusinessInfo, 
+                'BusinessInfoAddress' => $BusinessInfoAddress, 
+                'BillingInfo' => $BillingInfo, 
+                'BillingInfoAddress' => $BillingInfoAddress, 
+                'ShippingInfo' => $ShippingInfo, 
+                'ShippingInfoAddress' => $ShippingInfoAddress, 
+                'InvoiceItems' => $InvoiceItems
+        );
+
+        // Pass data into class for processing with PayPal and load the response array into $PayPalResult
+        $PayPalResult = $PayPal->Adaptive->CreateInvoice($PayPalRequestData);
+        echo '
';
+        echo "

Deprecated Notice: The classic CreateInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} else { + $invoiceDetails = array( + "currency_code" => "USD", // The three-character ISO 4217 currency code. + "note" => "This is a test invoice.", // A note to the payer. + "term" => "DueOnReceipt", // The payment term of the invoice, such as DueOnReceipt, Net30, etc. + "memo" => "This is a test invoice.", // A memo for the invoice. + ); + + $nameData = array( + "given_name" => "Tester", // The first name of the person. + "surname" => "Testerson" // The last name of the person. + ); + + $phonesData = array(); + + $phoneData = array( + "country_code" => "1", // The country code of the phone number. + "national_number" => "5555555555", // The phone number without the country code. + "phone_type" => "MOBILE" // The type of phone number. Valid Values: MOBILE, HOME, WORK, FAX. + ); + array_push($phonesData,$phoneData); + + $addressData = array( + "address_line_1" => "123 Main St.", // The first line of the address. + "admin_area_2" => "Grandview", // The city of the address. + "admin_area_1" => "MO", // The state of the address. + "postal_code" => "64030", // The postal code of the address. + "country_code" => "US" // The country code of the address. + ); + + $InvoiceItems = array(); + + $InvoiceItem = array( + 'name' => 'Test Widget 1', // Required. SKU or name of the item. + 'description' => 'This is a test widget #1', // Item description. + 'quantity' => '1', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => 'USD', // The currency code. + 'value' => '10.00' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $InvoiceItem = array( + 'name' => 'Test Widget 2', // Required. SKU or name of the item. + 'description' => 'This is a test widget #2', // Item description. + 'quantity' => '2', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => 'USD', // The currency code. + 'value' => '20.00' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $configurationData = array( + "partial_payment" => array("allow_partial_payment" => false), // Indicates whether to allow partial payments. true or false. + "tax_calculated_after_discount" => true, // Indicates whether the tax amount is calculated after applying the discount. true or false. + "allow_tip" => false, // Indicates whether to allow the payer to add a tip to the invoice. true or false. + ); + + $PayPalRequestData = array( + "detail" => $invoiceDetails, + "invoicer" => array( + "name" => $nameData, + "email_address" => "sb-j47z3s6571663@business.example.com", + "phones" => $phonesData, + "website" => "http://www.domain.com", + "address" => $addressData + ), + "primary_recipients" => array( + array( + "billing_info" => array( + "email_address" => "sb-j47z3s6571663@business.example.com", + "name" => $nameData, + "address" => $addressData + ), + ) + ), + "items" => $InvoiceItems, + "configuration" => $configurationData + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->CreateInvoice($PayPalRequestData); + echo '
';
+}
+print_r($PayPalResult);

From a0a7f3f650457b6e7adb892cc071de47244addab Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 24 Nov 2025 20:57:54 +0530
Subject: [PATCH 039/146] Conversion of MarkInvoiceAsPaid Completed

---
 samples/sample-methods/MarkInvoiceAsPaid.php | 63 ++++++++++++++++++++
 1 file changed, 63 insertions(+)
 create mode 100644 samples/sample-methods/MarkInvoiceAsPaid.php

diff --git a/samples/sample-methods/MarkInvoiceAsPaid.php b/samples/sample-methods/MarkInvoiceAsPaid.php
new file mode 100644
index 00000000..3c276c9f
--- /dev/null
+++ b/samples/sample-methods/MarkInvoiceAsPaid.php
@@ -0,0 +1,63 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+if( $api_mode === 'rest' ) {
+
+		// Prepare request arrays
+		$MarkInvoiceAsPaidFields = array(
+			'type' => 'EXTERNAL', 		                // Required.  ID of the invoice to mark paid.
+			'method' => 'CASH', 				// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+			'note' => 'This is a test note.', 		// Optional note associated with the payment.
+			'date' => '2012-02-19',
+			'InvoiceID' => 'INV2-X4CQ-CBN7-HRFF-JC9V',
+		);
+
+		$PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields);
+		$PayPalResult = $PayPal->MarkInvoiceAsPaid($PayPalRequestData);	
+		echo '
';	
+} else {
+	// Prepare request arrays
+	$MarkInvoiceAsPaidFields = array(
+		'InvoiceID' => 'INV2-GZWT-JZHS-FR3G-EDWA', 		// Required.  ID of the invoice to mark paid.
+		'Method' => 'Cash', 					// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+		'Note' => 'This is a test note.', 			// Optional note associated with the payment.
+		'Date' => '2012-02-19'					// Date the invoice was paid.
+	);
+
+	$PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields);
+	$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsPaid($PayPalRequestData);
+	echo '
';
+	echo "

Deprecated Notice: The classic CreateInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +// Write the contents of the response array to the screen for demo purposes. +print_r($PayPalResult); + + + + From 4c259f36109e7abafd4a78592b4806fb79dd6061 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 24 Nov 2025 21:00:50 +0530 Subject: [PATCH 040/146] Conversion of RemindInvoice Completed --- samples/sample-methods/RemindInvoice.php | 50 ++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 samples/sample-methods/RemindInvoice.php diff --git a/samples/sample-methods/RemindInvoice.php b/samples/sample-methods/RemindInvoice.php new file mode 100644 index 00000000..21526d27 --- /dev/null +++ b/samples/sample-methods/RemindInvoice.php @@ -0,0 +1,50 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +// Prepare request arrays +$RemindInvoiceFields = array( + 'InvoiceID' => 'INV2-NV29-RP49-7ERJ-8L6C', // ID of the invoice. +); + +$PayPalRequestData = array('RemindInvoiceFields' => $RemindInvoiceFields); + +if( $api_mode === 'rest' ){ + $RemindInvoiceFields['subject'] = 'This is the subject.'; + $RemindInvoiceFields['note'] = 'This is a note to the payer.'; + $PayPalResult = $PayPal->RemindInvoice($PayPalRequestData); + echo '
';
+    print_r($PayPalResult);
+} else {
+    $RemindInvoiceFields['Subject'] = 'This is the subject.';
+    $RemindInvoiceFields['NoteForPayer'] = 'This is a note to the payer.';
+    $PayPalResult = $PayPal->Adaptive->RemindInvoice($PayPalRequestData);
+
+    echo '
';
+    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + print_r($PayPalResult); +} From e910328470df24a5e145ed398b20a37d8a0ff824 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:06:18 +0530 Subject: [PATCH 041/146] Conversion of SendInvoice Completed --- samples/sample-methods/SendInvoice.php | 41 ++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 samples/sample-methods/SendInvoice.php diff --git a/samples/sample-methods/SendInvoice.php b/samples/sample-methods/SendInvoice.php new file mode 100644 index 00000000..c69b873e --- /dev/null +++ b/samples/sample-methods/SendInvoice.php @@ -0,0 +1,41 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$InvoiceID = 'INV2-G6YX-H4CK-6LUE-6JXP'; + +if( $api_mode === 'rest' ){ + $PayPalResult = $PayPal->SendInvoice($InvoiceID); + echo '
';
+} else {
+	$PayPalResult = $PayPal->Adaptive->SendInvoice($InvoiceID);
+	echo '
';
+    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); \ No newline at end of file From b6473e7d08f7f077f49ad1978b991551e80269f7 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:16:00 +0530 Subject: [PATCH 042/146] Conversion of SearchInvoices Completed --- samples/sample-methods/SearchInvoices.php | 90 +++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 samples/sample-methods/SearchInvoices.php diff --git a/samples/sample-methods/SearchInvoices.php b/samples/sample-methods/SearchInvoices.php new file mode 100644 index 00000000..99cfd3f8 --- /dev/null +++ b/samples/sample-methods/SearchInvoices.php @@ -0,0 +1,90 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +if( $api_mode === 'rest' ){ + $SearchInvoicesFields = array( + 'Page' => '1', // Required. Page number of result set, starting with 1 + 'PageSize' => '20' // Required. Number of result pages, between 1 and 100 + ); + + $Parameters = array( + 'Email' => '', // Email search string + 'MerchantEmail' => '', // Required. Email address of invoice creator. + 'InvoiceNumber' => '', // Invoice number search string + 'Status' => 'DRAFT', // Invoice status search + 'LowerAmount' => '', // Invoice amount search. It specifies the smallest amount to be returned. If you pass a value for this field, you must also pass a CurrencyCode value. + 'UpperAmount' => '', // Invoice amount search. It specifies the largest amount to be returned. If you pass a value for this field, you must also pass a CurrencyCode value. + 'CurrencyCode' => '', // Currency used for lower and upper amounts. + 'Memo' => '', // Invoice memo search string + ); + + $PayPalRequestData = array( + 'SearchInvoicesFields' => $SearchInvoicesFields, + 'Parameters' => $Parameters + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->SearchInvoices($PayPalRequestData); + echo '
';
+} else {
+	// Prepare request arrays
+	$SearchInvoicesFields = array(
+		'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 		// Required.  Email address of invoice creator.
+		'Page' => '1', 								// Required.  Page number of result set, starting with 1
+		'PageSize' => '1'							// Required.  Number of result pages, between 1 and 100
+	);
+
+	$Parameters = array(
+		'Email' => '', 								// Email search string
+		'RecipientName' => '', 						// Recipient search string
+		'BusinessName' => '', 						// Company search string
+		'InvoiceNumber' => '', 						// Invoice number search string
+		'Status' => '', 							// Invoice status search
+		'LowerAmount' => '', 						// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+		'UpperAmount' => '', 						// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+		'CurrencyCode' => '', 						// Currency used for lower and upper amounts.  
+		'Memo' => '', 								// Invoice memo search string
+		'Origin' => '' 								// Indicates whether the invoice was created by the website or by an API call.  Values are:  Web, API
+		//'InvoiceDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice date range filter
+		//'DueDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice due Date range filter
+		//'PaymentDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice payment date range filter.
+		//'CreationDate' => array('StartDate' => '', 'EndDate' => '')		// Invoice creation date range filter.
+	);
+
+	$PayPalRequestData = array(
+		'SearchInvoicesFields' => $SearchInvoicesFields, 
+		'Parameters' => $Parameters
+	);
+
+	$PayPalResult = $PayPal->Adaptive->SearchInvoices($PayPalRequestData);
+	echo '
';
+    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); From c58b632c02620b47a595b277f64719e5d38e2969 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:32:25 +0530 Subject: [PATCH 043/146] Conversion of MarkInvoiceAsRefunded Completed --- samples/sample-methods/GetPaymentOptions.php | 2 +- samples/sample-methods/MarkInvoiceAsPaid.php | 2 +- samples/sample-methods/RemindInvoice.php | 2 +- samples/sample-methods/SearchInvoices.php | 2 +- samples/sample-methods/SendInvoice.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/sample-methods/GetPaymentOptions.php b/samples/sample-methods/GetPaymentOptions.php index 458f7c9a..81f5f212 100644 --- a/samples/sample-methods/GetPaymentOptions.php +++ b/samples/sample-methods/GetPaymentOptions.php @@ -34,7 +34,7 @@ } else { $PayPalResult = $PayPal->Adaptive->GetPaymentOptions($PayKey); echo '
';
-	echo "

Deprecated Notice: The classic CreateInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + echo "

Deprecated Notice: The classic GetPaymentOptions method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; } print_r($PayPalResult); \ No newline at end of file diff --git a/samples/sample-methods/MarkInvoiceAsPaid.php b/samples/sample-methods/MarkInvoiceAsPaid.php index 3c276c9f..2d553b1a 100644 --- a/samples/sample-methods/MarkInvoiceAsPaid.php +++ b/samples/sample-methods/MarkInvoiceAsPaid.php @@ -52,7 +52,7 @@ $PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields); $PayPalResult = $PayPal->Adaptive->MarkInvoiceAsPaid($PayPalRequestData); echo '
';
-	echo "

Deprecated Notice: The classic CreateInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + echo "

Deprecated Notice: The classic MarkInvoiceAsPaid method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; } // Write the contents of the response array to the screen for demo purposes. diff --git a/samples/sample-methods/RemindInvoice.php b/samples/sample-methods/RemindInvoice.php index 21526d27..cb96a51f 100644 --- a/samples/sample-methods/RemindInvoice.php +++ b/samples/sample-methods/RemindInvoice.php @@ -45,6 +45,6 @@ $PayPalResult = $PayPal->Adaptive->RemindInvoice($PayPalRequestData); echo '
';
-    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + echo "

Deprecated Notice: The classic RemindInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; print_r($PayPalResult); } diff --git a/samples/sample-methods/SearchInvoices.php b/samples/sample-methods/SearchInvoices.php index 99cfd3f8..a4938f9f 100644 --- a/samples/sample-methods/SearchInvoices.php +++ b/samples/sample-methods/SearchInvoices.php @@ -84,7 +84,7 @@ $PayPalResult = $PayPal->Adaptive->SearchInvoices($PayPalRequestData); echo '
';
-    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + echo "

Deprecated Notice: The classic SearchInvoices method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; } print_r($PayPalResult); diff --git a/samples/sample-methods/SendInvoice.php b/samples/sample-methods/SendInvoice.php index c69b873e..59cc7487 100644 --- a/samples/sample-methods/SendInvoice.php +++ b/samples/sample-methods/SendInvoice.php @@ -35,7 +35,7 @@ } else { $PayPalResult = $PayPal->Adaptive->SendInvoice($InvoiceID); echo '
';
-    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + echo "

Deprecated Notice: The classic SendInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; } print_r($PayPalResult); \ No newline at end of file From 570be67198143b0fe1d61befef9c8929f74bdb5c Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:32:43 +0530 Subject: [PATCH 044/146] Conversion of MarkInvoiceAsRefunded Completed --- .../sample-methods/MarkInvoiceAsRefunded.php | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 samples/sample-methods/MarkInvoiceAsRefunded.php diff --git a/samples/sample-methods/MarkInvoiceAsRefunded.php b/samples/sample-methods/MarkInvoiceAsRefunded.php new file mode 100644 index 00000000..505173b6 --- /dev/null +++ b/samples/sample-methods/MarkInvoiceAsRefunded.php @@ -0,0 +1,66 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'rest' ) { + // Prepare request arrays + $MarkInvoiceAsRefundedFields = array( + 'note' => 'Amount refunded to customer.', + 'amount' => array( + 'currency_code' => 'USD', + 'value' => '10.00' + ), + 'method' => 'PAYPAL', + 'Date' => date('Y-m-d') + ); + + $PayPalRequestData = array( + 'InvoiceID' => 'INV2-X4CQ-CBN7-HRFF-JC9V', // Invoice ID of the invoice to mark refunded which has been paid + 'MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->MarkInvoiceAsRefunded($PayPalRequestData); + echo '
';
+} else {
+	// Prepare request arrays
+	$MarkInvoiceAsRefundedFields = array(
+		'InvoiceID' => 'INV2-GZWT-JZHS-FR3G-EDWA', 			// Required.  ID of the invoice to mark paid.
+		'Note' => 'This was refunded in person via cash.', 		// Optional note associated with the payment.
+		'Date' => date('Y-m-d')						// Date the invoice was paid.
+	);
+
+	$PayPalRequestData = array('MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsRefunded($PayPalRequestData);
+	echo '
';
+	echo "

Deprecated Notice: The classic MarkInvoiceAsRefunded method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +// Write the contents of the response array to the screen for demo purposes. +print_r($PayPalResult); From 1f4e92eb7c794c53bdae64c31950886550d53f6d Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:41:07 +0530 Subject: [PATCH 045/146] Conversion of CancelInvoice Completed --- samples/sample-methods/CancelInvoice.php | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 samples/sample-methods/CancelInvoice.php diff --git a/samples/sample-methods/CancelInvoice.php b/samples/sample-methods/CancelInvoice.php new file mode 100644 index 00000000..98698e08 --- /dev/null +++ b/samples/sample-methods/CancelInvoice.php @@ -0,0 +1,56 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret + +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +// Prepare request arrays +$CancelInvoiceFields = array( + 'InvoiceID' => 'INV2-3283-QFCE-5L2E-4FCH', // ID of the invoice. + 'Subject' => 'Invoice has been canceled.', // Subject of the cancelation notification. + 'NoteForPayer' => 'Note for Payer.', // Note to send the payer within the cancelation notification. + 'SendCopyToMerchant' => 'true' // Indicates whether to send a copy of the cancelation notification to the merchant. Values are: true/false +); + +if( $api_mode === 'rest' ) { + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->CancelInvoice($CancelInvoiceFields); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+
+} else {
+	$PayPalRequestData = array('CancelInvoiceFields' => $CancelInvoiceFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->CancelInvoice($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic CancelInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); From 339bd66a6073ad6a6f717e158017ea1a016d6993 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:48:07 +0530 Subject: [PATCH 046/146] Conversion of CreateAndSendInvoice Completed --- .../sample-methods/CreateAndSendInvoice.php | 243 ++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 samples/sample-methods/CreateAndSendInvoice.php diff --git a/samples/sample-methods/CreateAndSendInvoice.php b/samples/sample-methods/CreateAndSendInvoice.php new file mode 100644 index 00000000..fec87281 --- /dev/null +++ b/samples/sample-methods/CreateAndSendInvoice.php @@ -0,0 +1,243 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'rest' ) { + + $invoiceDetails = array( + "currency_code" => "USD", // The three-character ISO 4217 currency code. + "note" => "This is a test invoice.", // A note to the payer. + "term" => "DueOnReceipt", // The payment term of the invoice, such as DueOnReceipt, Net30, etc. + "memo" => "This is a test invoice.", // A memo for the invoice. + ); + + $nameData = array( + "given_name" => "Tester", // The first name of the person. + "surname" => "Testerson" // The last name of the person. + ); + + $phonesData = array(); + + $phoneData = array( + "country_code" => "1", // The country code of the phone number. + "national_number" => "5555555555", // The phone number without the country code. + "phone_type" => "MOBILE" // The type of phone number. Valid Values: MOBILE, HOME, WORK, FAX. + ); + array_push($phonesData,$phoneData); + + $addressData = array( + "address_line_1" => "123 Main St.", // The first line of the address. + "admin_area_2" => "Grandview", // The city of the address. + "admin_area_1" => "MO", // The state of the address. + "postal_code" => "64030", // The postal code of the address. + "country_code" => "US" // The country code of the address. + ); + + $InvoiceItems = array(); + + $InvoiceItem = array( + 'name' => 'Test Widget 1', // Required. SKU or name of the item. + 'description' => 'This is a test widget #1', // Item description. + 'quantity' => '1', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => 'USD', // The currency code. + 'value' => '10.00' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $InvoiceItem = array( + 'name' => 'Test Widget 2', // Required. SKU or name of the item. + 'description' => 'This is a test widget #2', // Item description. + 'quantity' => '2', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => 'USD', // The currency code. + 'value' => '20.00' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $configurationData = array( + "partial_payment" => array("allow_partial_payment" => false), // Indicates whether to allow partial payments. true or false. + "tax_calculated_after_discount" => true, // Indicates whether the tax amount is calculated after applying the discount. true or false. + "allow_tip" => false, // Indicates whether to allow the payer to add a tip to the invoice. true or false. + ); + + $PayPalRequestData = array( + "detail" => $invoiceDetails, + "invoicer" => array( + "name" => $nameData, + "email_address" => "sb-j47z3s6571663@business.example.com", + "phones" => $phonesData, + "website" => "http://www.domain.com", + "address" => $addressData + ), + "primary_recipients" => array( + array( + "billing_info" => array( + "email_address" => "sb-j47z3s6571663@business.example.com", + "name" => $nameData, + "address" => $addressData + ), + ) + ), + "items" => $InvoiceItems, + "configuration" => $configurationData + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->CreateAndSendInvoice($PayPalRequestData); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+
+} else {
+        // Prepare request arrays
+        $CreateInvoiceFields = array(
+                'MerchantEmail' => 'sandbo_1215254764_biz@angelleye.com', 				// Required.  Merchant email address.
+                'PayerEmail' => 'drew@angelleye.com', 							// Required.  Payer email address.
+                'Number' => 'ABC-ZZZz', 								// Unique ID for the invoice.
+                'CurrencyCode' => 'USD', 								// Required.  Currency used for all invoice item amounts and totals.
+                'InvoiceDate' => '', 									// Date on which the invoice is enabled.
+                'DueDate' => '', 									// Date on which the invoice payment is due.
+                'PaymentTerms' => 'DueOnReceipt', 							// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+                'DiscountPercent' => '', 								// Discount percent applied to the invoice.
+                'DiscountAmount' => '', 								// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+                'Terms' => '', 										// General terms for the invoice.
+                'Note' => 'This is a test invoice.', 							// Note to the payer company.
+                'MerchantMemo' => 'This is a test invoice.', 						// Memo for bookkeeping that is private to the merchant.
+                'ShippingAmount' => '10.00', 								// Cost of shipping
+                'ShippingTaxName' => '', 								// Name of the applicable tax on the shipping cost.
+                'ShippingTaxRate' => '', 								// Rate of the applicable tax on the shipping cost.
+                'LogoURL' => 'https://www.usbswiper.com/images/angelley-clients/cpp-header-image.jpg'	// Complete URL to an external image used as the logo, if any.
+        );
+                                                                
+        $BusinessInfo = array(
+                'FirstName' => 'Tester', 			// First name of the company contact.
+                'LastName' => 'Testerson', 			// Last name of the company contact.
+                'BusinessName' => 'Testers, LLC', 		// Company business name.
+                'Phone' => '555-555-5555', 			// Phone number for contacting the company.
+                'Fax' => '555-555-5556', 			// Fax number used by the company.
+                'Website' => 'http://www.domain.com', 		// Website used by the company.
+                'Custom' => 'Some custom info.' 		// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $BusinessInfoAddress = array(
+                'Line1' => '123 Main St.', 		// Required. First line of address.
+                'Line2' => '', 				// Second line of address.
+                'City' => 'Grandview', 			// Required. City of the address.
+                'State' => 'MO', 			// State for the address.
+                'PostalCode' => '64030', 		// Postal code of the address
+                'CountryCode' => 'US'			// Required.  Country code of the address.
+        );
+
+        $BillingInfo = array(
+                'FirstName' => '', 		// First name of the company contact.
+                'LastName' => '', 		// Last name of the company contact.
+                'BusinessName' => '', 		// Company business name.
+                'Phone' => '', 			// Phone number for contacting the company.
+                'Fax' => '', 			// Fax number used by the company.
+                'Website' => '', 		// Website used by the company.
+                'Custom' => '' 			// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $BillingInfoAddress = array(
+                'Line1' => '', 			// Required. First line of address.
+                'Line2' => '', 			// Second line of address.
+                'City' => '', 			// Required. City of the address.
+                'State' => '', 			// State for the address.
+                'PostalCode' => '', 		// Postal code of the address
+                'CountryCode' => ''		// Required.  Country code of the address.
+        );
+
+        $ShippingInfo = array(
+                'FirstName' => '', 		// First name of the company contact.
+                'LastName' => '', 		// Last name of the company contact.
+                'BusinessName' => '', 		// Company business name.
+                'Phone' => '', 			// Phone number for contacting the company.
+                'Fax' => '', 			// Fax number used by the company.
+                'Website' => '', 		// Website used by the company.
+                'Custom' => '' 			// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $ShippingInfoAddress = array(
+                'Line1' => '', 			// Required. First line of address.
+                'Line2' => '', 			// Second line of address.
+                'City' => '', 			// Required. City of the address.
+                'State' => '', 			// State for the address.
+                'PostalCode' => '', 		// Postal code of the address
+                'CountryCode' => ''		// Required.  Country code of the address.
+        );
+
+        // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
+        // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
+
+        $InvoiceItems = array();
+
+        $InvoiceItem = array(
+                'Name' => 'Test Widget 1', 				// Required.  SKU or name of the item.
+                'Description' => 'This is a test widget #1', 		// Item description.
+                'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+                'Quantity' => '1', 					// Required.  Item count.  Values are:  0 to 10000
+                'UnitPrice' => '10.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+                'TaxName' => '', 					// Name of the applicable tax.
+                'TaxRate' => ''						// Rate of the applicable tax.
+        );
+        array_push($InvoiceItems,$InvoiceItem);
+
+        $InvoiceItem = array(
+                'Name' => 'Test Widget 2', 				// Required.  SKU or name of the item.
+                'Description' => 'This is a test widget #2', 		// Item description.
+                'Date' => '2012-02-18', 				// Date on which the product or service was provided.
+                'Quantity' => '2', 					// Required.  Item count.  Values are:  0 to 10000
+                'UnitPrice' => '20.00', 				// Required.  Price of the item, in the currency specified by the invoice.
+                'TaxName' => '', 					// Name of the applicable tax.
+                'TaxRate' => ''						// Rate of the applicable tax.
+        );
+        array_push($InvoiceItems,$InvoiceItem);
+
+        $PayPalRequestData = array(
+                'CreateInvoiceFields' => $CreateInvoiceFields, 
+                'BusinessInfo' => $BusinessInfo, 
+                //'BusinessInfoAddress' => $BusinessInfoAddress, 
+                //'BillingInfo' => $BillingInfo, 
+                //'BillingInfoAddress' => $BillingInfoAddress, 
+                //'ShippingInfo' => $ShippingInfo, 
+                //'ShippingInfoAddress' => $ShippingInfoAddress, 
+                'InvoiceItems' => $InvoiceItems
+        );
+
+        // Pass data into class for processing with PayPal and load the response array into $PayPalResult
+        $PayPalResult = $PayPal->Adaptive->CreateAndSendInvoice($PayPalRequestData);
+
+        // Write the contents of the response array to the screen for demo purposes.
+        echo '
';
+        echo "

Deprecated Notice: The classic CreateAndSendInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + + +print_r($PayPalResult); From 1cded427f5d0a5f20d1c43efc22ce38ad12072f6 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 19:53:57 +0530 Subject: [PATCH 047/146] Conversion of DeleteInvoice Completed --- samples/sample-methods/DeleteInvoice.php | 45 ++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 samples/sample-methods/DeleteInvoice.php diff --git a/samples/sample-methods/DeleteInvoice.php b/samples/sample-methods/DeleteInvoice.php new file mode 100644 index 00000000..e2d15558 --- /dev/null +++ b/samples/sample-methods/DeleteInvoice.php @@ -0,0 +1,45 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$InvoiceID = 'INV2-YMM7-96UZ-2ZR5-HDP6'; + +if( $api_mode === 'rest' ) { + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->DeleteInvoice($InvoiceID); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+} else {
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->DeleteInvoice($InvoiceID);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic DeleteInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} +print_r($PayPalResult); From 243b8b26d425c65d34a670543ef06c844c97ced0 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 25 Nov 2025 22:59:57 +0530 Subject: [PATCH 048/146] Conversion of DoDirectPayment Completed --- samples/sample-methods/DoDirectPayment.php | 131 +++++++++++++++++++++ src/angelleye/PayPal/PayPalREST.php | 28 ++++- 2 files changed, 153 insertions(+), 6 deletions(-) create mode 100644 samples/sample-methods/DoDirectPayment.php diff --git a/samples/sample-methods/DoDirectPayment.php b/samples/sample-methods/DoDirectPayment.php new file mode 100644 index 00000000..cd5a9afd --- /dev/null +++ b/samples/sample-methods/DoDirectPayment.php @@ -0,0 +1,131 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$DPFields = array( + 'paymentaction' => 'Sale', // How you want to obtain payment. Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture. Sale indicates that this is a final sale for which you are requesting payment. Default is Sale. + 'ipaddress' => $_SERVER['REMOTE_ADDR'], // Required. IP address of the payer's browser. + 'returnfmfdetails' => '1' // Flag to determine whether you want the results returned by FMF. 1 or 0. Default is 0. +); + +$CCDetails = array( + 'creditcardtype' => 'Visa', // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. + 'acct' => '4716392328094345', // Required. Credit card number. No spaces or punctuation. + 'expdate' => '022026', // Required. Credit card expiration date. Format is MMYYYY + 'cvv2' => '456', // Requirements determined by your PayPal account settings. Security digits for credit card. + 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY + 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. +); + +$PayerInfo = array( + 'email' => 'sandbox@angelleye.com', // Email address of payer. + 'payerid' => '', // Unique PayPal customer ID for payer. + 'payerstatus' => '', // Status of payer. Values are verified or unverified + 'business' => '' // Payer's business name. +); + +$PayerName = array( + 'salutation' => '', // Payer's salutation. 20 char max. + 'firstname' => 'Tester', // Payer's first name. 25 char max. + 'middlename' => '', // Payer's middle name. 25 char max. + 'lastname' => 'Testerson', // Payer's last name. 25 char max. + 'suffix' => '' // Payer's suffix. 12 char max. +); + +$BillingAddress = array( + 'street' => '707 W. Bay Drive', // Required. First street address. + 'street2' => '', // Second street address. + 'city' => 'Largo', // Required. Name of City. + 'state' => 'FL', // Required. Name of State or Province. + 'countrycode' => 'US', // Required. Country code. + 'zip' => '33770', // Required. Postal code of payer. + 'phonenum' => '' // Phone Number of payer. 20 char max. +); + +$ShippingAddress = array( + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountrycode' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '' // Phone number for shipping address. 20 char max. +); + +$PaymentDetails = array( + 'amt' => '3.00', // Required. Total amount of order, including shipping, handling, and tax. + 'currencycode' => 'USD', // Required. Three-letter currency code. Default is USD. + 'itemamt' => '', // Required if you include itemized cart details. (L_AMTn, etc.) Subtotal of items not including S&H, or tax. + 'shippingamt' => '', // Total shipping costs for the order. If you specify shippingamt, you must also specify itemamt. + 'handlingamt' => '', // Total handling costs for the order. If you specify handlingamt, you must also specify itemamt. + 'taxamt' => '', // Required if you specify itemized cart tax details. Sum of tax for all items on the order. Total sales tax. + 'desc' => 'Testing Payments Pro DESC Field', // Description of the order the customer is purchasing. 127 char max. + 'custom' => 'TEST', // Free-form field for your own use. 256 char max. + 'invnum' => 'ZZZ-123-ABC', // Your own invoice or tracking number + 'buttonsource' => '', // An ID code for use by 3rd party apps to identify transactions. + 'notifyurl' => '' // URL for receiving Instant Payment Notifications. This overrides what your profile is set to use. +); + +$OrderItems = array(); +$Item = array( + 'l_name' => 'Test Widget', // Item Name. 127 char max. + 'l_desc' => 'This is a test widget description.', // Item description. 127 char max. + 'l_amt' => '1.00', // Cost of individual item. + 'l_number' => 'ABC-123', // Item Number. 127 char max. + 'l_qty' => '1', // Item quantity. Must be any positive integer. + 'l_taxamt' => '', // Item's sales tax amount. + 'l_ebayitemnumber' => '', // eBay auction number of item. + 'l_ebayitemauctiontxnid' => '', // eBay transaction ID of purchased item. + 'l_ebayitemorderid' => '' // eBay order ID for the item. +); +array_push($OrderItems, $Item); + +$Item = array( + 'l_name' => 'Test Widget 2', // Item Name. 127 char max. + 'l_desc' => 'This is a test widget description.', // Item description. 127 char max. + 'l_amt' => '2.00', // Cost of individual item. + 'l_number' => 'ABC-XYZ', // Item Number. 127 char max. + 'l_qty' => '1', // Item quantity. Must be any positive integer. + 'l_taxamt' => '', // Item's sales tax amount. + 'l_ebayitemnumber' => '', // eBay auction number of item. + 'l_ebayitemauctiontxnid' => '', // eBay transaction ID of purchased item. + 'l_ebayitemorderid' => '' // eBay order ID for the item. +); +array_push($OrderItems, $Item); + +$PayPalRequestData = array( + 'DPFields' => $DPFields, + 'CCDetails' => $CCDetails, + 'PayerInfo' => $PayerInfo, + 'PayerName' => $PayerName, + 'BillingAddress' => $BillingAddress, + 'PaymentDetails' => $PaymentDetails, + 'OrderItems' => $OrderItems +); + +$PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData); + +if( $api_mode === 'rest' ){ + $_SESSION['transaction_id'] = isset($PayPalResult['RESPONSE']['id']) ? $PayPalResult['RESPONSE']['id'] : ''; +} else { + $_SESSION['transaction_id'] = isset($PayPalResult['TRANSACTIONID']) ? $PayPalResult['TRANSACTIONID'] : ''; +} +echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index d8586d56..303ff120 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -611,6 +611,8 @@ private function getApprovalUrl($links)
     public function DoDirectPayment($paymentData) {
         $paymentsMappedData = [];
 
+        $PaymentAmount = !empty($paymentData['PaymentDetails']['amt']) ? $paymentData['PaymentDetails']['amt'] : 0.00;
+        $PaymentCurrency = !empty($paymentData['PaymentDetails']['currencycode']) ? $paymentData['PaymentDetails']['currencycode'] : '';
         $paymentsMappedData['intent'] = !empty($paymentData['DPFields']['paymentaction']) ? $paymentData['DPFields']['paymentaction'] : 'sale';
         $paymentsMappedData['purchase_units'] = [
             [
@@ -645,12 +647,26 @@ public function DoDirectPayment($paymentData) {
 
         // Handle Response
         if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
-            $responseSimplified = array(
-                'SUCCESS' => true,
-                'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
-                'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
-                'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
-            );
+
+            if( $this->api_upgrade ) {
+                $responseSimplified = array(
+                    'SUCCESS' => true,
+                    'ACK' => 'Success',
+                    'AMT' => $PaymentAmount,
+                    'CURRENCYCODE' => $PaymentCurrency,
+                    'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                    'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                    'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+                );
+
+            } else {
+                $responseSimplified = array(
+                    'SUCCESS' => true,
+                    'STATUSCODE' => !empty($response['status_code']) ? $response['status_code'] : 0,
+                    'RESPONSE' => !empty($response['body']) ? $response['body'] : [],
+                    'RAWRESPONSE' => !empty($response['raw_response']) ? $response['raw_response'] : [],
+                );
+            }
         } else {
             $responseSimplified = array(
                 'SUCCESS' => false,

From 86a50fabc2e63aaacfbe20f79c91f0bafcef41e6 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 26 Nov 2025 21:44:59 +0530
Subject: [PATCH 049/146] Conversion of GetInvoiceDetails Completed

---
 samples/sample-methods/GetInvoiceDetails.php | 45 ++++++++++++++++++++
 1 file changed, 45 insertions(+)
 create mode 100644 samples/sample-methods/GetInvoiceDetails.php

diff --git a/samples/sample-methods/GetInvoiceDetails.php b/samples/sample-methods/GetInvoiceDetails.php
new file mode 100644
index 00000000..289f0413
--- /dev/null
+++ b/samples/sample-methods/GetInvoiceDetails.php
@@ -0,0 +1,45 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$InvoiceID = 'INV2-AB7V-NL6F-MW2A-HRUT';
+
+if( $api_mode === 'rest' ) {
+	$PayPalResult = $PayPal->GetInvoiceDetails($InvoiceID);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+} else {
+	$PayPalResult = $PayPal->Adaptive->GetInvoiceDetails($InvoiceID);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic GetInvoiceDetails method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); From ee7a2e3725180fc114eae6aaabb62b65cdb59123 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Wed, 26 Nov 2025 22:05:43 +0530 Subject: [PATCH 050/146] Conversion of MassPay Completed --- samples/sample-methods/MassPay.php | 118 ++++++++++++++++++++++++++++ src/angelleye/PayPal/PayPalREST.php | 12 +++ 2 files changed, 130 insertions(+) create mode 100644 samples/sample-methods/MassPay.php diff --git a/samples/sample-methods/MassPay.php b/samples/sample-methods/MassPay.php new file mode 100644 index 00000000..4cef06c8 --- /dev/null +++ b/samples/sample-methods/MassPay.php @@ -0,0 +1,118 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +if( $api_mode === 'rest' ){ + + // Prepare request arrays + $SenderBatchHeaders = array( + 'sender_batch_id' => uniqid("batch_"), // A unique identifier of the batch payout. Must be unique for each payout. + "email_subject" => "Test MassPay via PayPal REST API", // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients. 255 char max. + "email_message" => "You have received a payout!", // The message that PayPal sends to the recipients of the payout email. 255 char max. + ); + + // Typically, you'll loop through some sort of records to build your MPItems array. + // Here I simply include 3 items individually. + + $Item1 = array( + "recipient_type" => "EMAIL", // The type of recipient. Must be EMAIL or PHONE. + "amount" => array( + "value" => "0.01", // The amount to be paid to the recipient. + "currency" => "USD" // The currency code. + ), + "receiver" => "andrew_1342623385_per@angelleye.com", // The recipient's email address. + "note" => "Thanks for your work!", // A note to the recipient. + "sender_item_id" => "item_1" // A unique identifier for the item in the payout batch. + ); + + $Item2 = array( + "recipient_type" => "EMAIL", // The type of recipient. Must be EMAIL or PHONE. + "amount" => array( + "value" => "0.01", // The amount to be paid to the recipient. + "currency" => "USD" // The currency code. + ), + "receiver" => "usb_1329725429_biz@angelleye.com", // The recipient's email address. + "note" => "Payment for services", // A note to the recipient. + "sender_item_id" => "item_2" // A unique identifier for the item in the payout batch. + ); + + $Item3 = array( + "recipient_type" => "EMAIL", // The type of recipient. Must be EMAIL or PHONE. + "amount" => array( + "value" => "0.01", // The amount to be paid to the recipient. + "currency" => "USD" // The currency code. + ), + "receiver" => "andrew_1277258815_per@angelleye.com", // The recipient's email address. + "note" => "Thank you!", // A note to the recipient. + "sender_item_id" => "item_3" // A unique identifier for the item in the payout batch. + ); + + $Items = array($Item1, $Item2, $Item3); // etc + + $PayPalRequestData = array('sender_batch_header'=>$SenderBatchHeaders, 'items' => $Items); +} else { + + // Prepare request arrays + $MPFields = array( + 'emailsubject' => 'Test MassPay', // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients. 255 char max. + 'currencycode' => 'USD', // Three-letter currency code. + 'receivertype' => 'EmailAddress' // Indicates how you identify the recipients of payments in this call to MassPay. Must be EmailAddress or UserID + ); + + // Typically, you'll loop through some sort of records to build your MPItems array. + // Here I simply include 3 items individually. + + $Item1 = array( + 'l_email' => 'andrew_1342623385_per@angelleye.com', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two. + 'l_receiverid' => '', // Required. ReceiverID of recipient. Must specify this or email address, but not both. + 'l_amt' => '10.00', // Required. Payment amount. + 'l_uniqueid' => '', // Transaction-specific ID number for tracking in an accounting system. + 'l_note' => '' // Custom note for each recipient. + ); + + $Item2 = array( + 'l_email' => 'usb_1329725429_biz@angelleye.com', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two. + 'l_receiverid' => '', // Required. ReceiverID of recipient. Must specify this or email address, but not both. + 'l_amt' => '10.00', // Required. Payment amount. + 'l_uniqueid' => '', // Transaction-specific ID number for tracking in an accounting system. + 'l_note' => '' // Custom note for each recipient. + ); + + $Item3 = array( + 'l_email' => 'andrew_1277258815_per@angelleye.com', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two. + 'l_receiverid' => '', // Required. ReceiverID of recipient. Must specify this or email address, but not both. + 'l_amt' => '10.00', // Required. Payment amount. + 'l_uniqueid' => '', // Transaction-specific ID number for tracking in an accounting system. + 'l_note' => '' // Custom note for each recipient. + ); + + $MPItems = array($Item1, $Item2, $Item3); // etc + + $PayPalRequestData = array('MPFields'=>$MPFields, 'MPItems' => $MPItems); +} + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$PayPalResult = $PayPal->MassPay($PayPalRequestData); + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 303ff120..2332144e 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1361,6 +1361,18 @@ public function MassPay($DataArray) {
             $response = $this->makeRequest('/v1/payments/payouts', 'POST', $DataArray);
 
             if ($response['status_code'] === 201) {
+
+                if( $this->api_upgrade ) {
+                    return [
+                        'ACK' => 'Success',
+                        'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
+                        'success' => true,
+                        'L_LONGMESSAGE' => isset($body['message']) ? $body['message'] : '',
+                        'status' => isset($response['body']['status']) ? $response['body']['status'] : $response['status_code'],
+                        'full_response' => $response['body'],
+                        'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                    ];
+                }
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],

From 063af3919fa90ce7649ff1edb9526792cd45760b Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 26 Nov 2025 22:11:32 +0530
Subject: [PATCH 051/146] Conversion of Refund Completed

---
 samples/sample-methods/Refund.php | 86 +++++++++++++++++++++++++++++++
 1 file changed, 86 insertions(+)
 create mode 100644 samples/sample-methods/Refund.php

diff --git a/samples/sample-methods/Refund.php b/samples/sample-methods/Refund.php
new file mode 100644
index 00000000..b2a22b53
--- /dev/null
+++ b/samples/sample-methods/Refund.php
@@ -0,0 +1,86 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+
+if( $api_mode === 'rest' ) {
+
+	// Prepare request arrays
+	$RefundFields = array(
+		'value' => '25.00',                            // Amount to refund.  Must not exceed the amount of the original payment.
+			'currency_code' => 'USD',        		// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+	);
+
+	$PayPalRequestData = array(
+		'transaction_id' => '0WU82026WU6763052', 
+		'refund_fields' => array(
+					'amount' => $RefundFields,
+					"note_to_payer" => "Refund issued"
+			),
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Refund($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+
+} else {
+
+	// Prepare request arrays
+	$RefundFields = array(
+		'CurrencyCode' => 'USD', 			// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+		'PayKey' => '',  				// Required.  The key used to create the payment that you want to refund.
+		'TransactionID' => '9AB88689BB076712X', 	// Required.  The PayPal transaction ID associated with the payment that you want to refund.
+		'TrackingID' => ''				// Required.  The tracking ID associated with the payment that you want to refund.
+	);
+
+	$Receivers = array();
+	$Receiver = array(
+		'Email' => 'agb_1296755685_biz@angelleye.com',	// A receiver's email address. 
+		'Amount' => '100.00', 				// Amount to be debited to the receiver's account.
+		'Primary' => '', 				// Set to true to indicate a chained payment.  Only one receiver can be a primary receiver.  Omit this field, or set to false for simple and parallel payments.
+		'InvoiceID' => '', 				// The invoice number for the payment.  This field is only used in Pay API operation.
+		'PaymentType' => 'GOODS'			// The transaction subtype for the payment.  Allowable values are: GOODS, SERVICE
+	);
+
+	array_push($Receivers, $Receiver);
+
+	$PayPalRequestData = array(
+		'RefundFields' => $RefundFields, 
+		'Receivers' => $Receivers
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->Refund($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic Refund method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); \ No newline at end of file From d34a22fa82d3c2add48f0c273419e32b4ceca134 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Wed, 26 Nov 2025 22:18:13 +0530 Subject: [PATCH 052/146] Conversion of RequestPermissions Completed --- samples/sample-methods/RequestPermissions.php | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 samples/sample-methods/RequestPermissions.php diff --git a/samples/sample-methods/RequestPermissions.php b/samples/sample-methods/RequestPermissions.php new file mode 100644 index 00000000..405f9d46 --- /dev/null +++ b/samples/sample-methods/RequestPermissions.php @@ -0,0 +1,83 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'rest' ) { + + $PayPalResult = $PayPal->RequestPermissions(); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+
+} else {
+
+	// Prepare request arrays
+	$Scope = array(
+		'EXPRESS_CHECKOUT', 
+		'DIRECT_PAYMENT', 
+	/*	'SETTLEMENT_CONSOLIDATION', 
+		'SETTLEMENT_REPORTING', 
+		'AUTH_CAPTURE', 
+		'MOBILE_CHECKOUT', 
+	*/	'BILLING_AGREEMENT', 
+		'REFERENCE_TRANSACTION', 
+	/*	'AIR_TRAVEL', 
+		'MASS_PAY', 
+	*/	'TRANSACTION_DETAILS',
+		'TRANSACTION_SEARCH',
+		'RECURRING_PAYMENTS',
+		'ACCOUNT_BALANCE',
+		'ENCRYPTED_WEBSITE_PAYMENTS',
+		'REFUND',
+		'NON_REFERENCED_CREDIT',
+		'BUTTON_MANAGER',
+		'MANAGE_PENDING_TRANSACTION_STATUS',
+		'RECURRING_PAYMENT_REPORT',
+		'EXTENDED_PRO_PROCESSING_REPORT',
+		'EXCEPTION_PROCESSING_REPORT',
+		'ACCOUNT_MANAGEMENT_PERMISSION',
+		'ACCESS_BASIC_PERSONAL_DATA',
+		'ACCESS_ADVANCED_PERSONAL_DATA'
+	);
+
+	$RequestPermissionsFields = array(
+		'Scope' => $Scope, 						// Required.   
+		'Callback' => $domain . 'samples/rest/RequestPermissions.php'	// Required.  Your callback function that specifies actions to take after the account holder grants or denies the request.
+	);
+
+	$PayPalRequestData = array('RequestPermissionsFields' => $RequestPermissionsFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->RequestPermissions($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic RequestPermissions method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + +} + +print_r($PayPalResult); From 2459602fd3992a8e42277808868b9dfb6dda3ed0 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Wed, 26 Nov 2025 22:30:58 +0530 Subject: [PATCH 053/146] Conversion of UpdateAuthorization Completed --- .../sample-methods/UpdateAuthorization.php | 46 +++++++++++++++++++ src/angelleye/PayPal/PayPalREST.php | 12 ++++- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 samples/sample-methods/UpdateAuthorization.php diff --git a/samples/sample-methods/UpdateAuthorization.php b/samples/sample-methods/UpdateAuthorization.php new file mode 100644 index 00000000..253a052b --- /dev/null +++ b/samples/sample-methods/UpdateAuthorization.php @@ -0,0 +1,46 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if ( $api_mode === 'rest' ) { + + $transactionID = '1DX651469Y560601N'; + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->UpdateAuthorization($transactionID); + +} else { + + // Prepare request arrays + $UAFields = array( + 'transactionid' => '1DX651469Y560601N', // Required. The value of the authorization's transaction identification number returned by a PayPal product. Char length: 17 single-byte chars. + 'ipaddress' => $_SERVER['REMOTE_ADDR'] // IP address of the customer. + ); + + $PayPalRequestData = array('UAFields'=>$UAFields); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->UpdateAuthorization($PayPalRequestData); +} + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 2332144e..ca7dee9a 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1291,8 +1291,18 @@ public function UpdateAuthorization($transactionId)
     {
         try {
             $response = $this->makeRequest('/v2/payments/authorizations/' . $transactionId . '/reauthorize', 'POST');
+            if ( $response['status_code'] >= 200 && $response['status_code'] < 300 ) {
 
-            if ($response['status_code'] === 200) {
+                if( $this->api_upgrade ) {
+                    return [
+                        'success' => true,
+                        'TIMESTAMP' => '2025-11-26T16:51:14Z',
+                        'ACK' => 'Success',
+                        'L_LONGMESSAGE0' => isset($response['body']['details']['message']) ? $response['body']['details']['message'] : '',
+                        'order' => $response['body'],
+                        'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                    ];
+                }
                 return [
                     'success' => true,
                     'order' => $response['body']

From ae08cabbfcfade87369eda830b026859bd1a5086 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 26 Nov 2025 22:44:27 +0530
Subject: [PATCH 054/146] Conversion of UpdateRecurringPaymentsProfile
 Completed

---
 .../UpdateRecurringPaymentsProfile.php        | 130 ++++++++++++++++++
 src/angelleye/PayPal/PayPalREST.php           |  15 +-
 2 files changed, 144 insertions(+), 1 deletion(-)
 create mode 100644 samples/sample-methods/UpdateRecurringPaymentsProfile.php

diff --git a/samples/sample-methods/UpdateRecurringPaymentsProfile.php b/samples/sample-methods/UpdateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..82924332
--- /dev/null
+++ b/samples/sample-methods/UpdateRecurringPaymentsProfile.php
@@ -0,0 +1,130 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+
+if ( $api_mode === 'rest' ) { 
+
+	$ReplaceFields = array(
+		"op" => "replace",
+			"path" => "/shipping_amount",
+			"value" => [
+					"currency_code" => "USD",
+					"value" => "1.00"
+			]
+	);
+
+	$Patches = array($ReplaceFields);
+
+	// Prepare request arrays
+	$PayPalRequestData = array(
+			'subscription_id' => 'I-SBAGHVRFVY0X',
+			'patches' => $Patches,
+	);
+
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->UpdateSubscriptionProfile($PayPalRequestData);
+
+} else {
+
+	// Prepare request arrays
+	$URPPFields = array(
+		'profileid' => 'I-TC0V2G64PKR0', 		// Required.  Recurring payments ID.
+		'note' => '', 					// Note about the reason for the update to the profile.  Included in EC profile notification emails and in details pages.
+		'desc' => '', 					// Description of the recurring payment profile.
+		'subscribername' => '', 			// Full name of the person receiving the product or service paid for by the recurring payment profile.
+		'profilereference' => '', 			// The merchant's own unique reference or invoice number.
+		'additionalbillingcycles' => '', 		// The number of additional billing cycles to add to this profile.
+		'amt' => '1.2', 				// Billing amount for each cycle in the subscription, not including shipping and tax.  Express Checkout profiles can only be updated by 20% every 180 days.
+		'shippingamt' => '', 				// Shipping amount for each billing cycle during the payment period.
+		'taxamt' => '', 				// Tax amount for each billing cycle during the payment period.
+		'outstandingamt' => '', 			// The current past-due or outstanding amount.  You can only decrease this amount.  
+		'autobilloutamt' => '', 			// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.
+		'maxfailedpayments' => '', 			// The number of failed payments allowed before the profile is automatically suspended.  The specified value cannot be less than the current number of failed payments for the profile.
+		'profilestartdate' => ''			// The date when the billing for this profile begins.  UTC/GMT format.
+	);
+
+	$BillingAddress = array(
+		'street' => '', 		// Required.  First street address.
+		'street2' => '', 		// Second street address.
+		'city' => '', 			// Required.  Name of City.
+		'state' => '', 			// Required. Name of State or Province.
+		'countrycode' => '', 		// Required.  Country code.
+		'zip' => '', 			// Required.  Postal code of payer.
+		'phonenum' => '' 		// Phone Number of payer.  20 char max.
+	);
+
+	$ShippingAddress = array(
+		'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+		'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+		'shiptostreet2' => '', 		// Second street address.  100 char max.
+		'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+		'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+		'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+		'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+		'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+	);
+
+	$BillingPeriod = array(
+		'trialbillingperiod' => '', 
+		'trialbillingfrequency' => '', 
+		'trialtotalbillingcycles' => '', 
+		'trialamt' => '', 
+		'billingperiod' => '', 			// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+		'billingfrequency' => '', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+		'totalbillingcycles' => '', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+		'amt' => '', 				// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+		'currencycode' => '', 			// Required.  Three-letter currency code.
+	);
+
+	$CCDetails = array(
+		'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+		'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+		'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+		'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+		'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+		'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+	);
+
+	$PayerInfo = array(
+		'email' => '', 			// Payer's email address.
+		'firstname' => '', 		// Required.  Payer's first name.
+		'lastname' => ''		// Required.  Payer's last name.
+	);
+				
+	$PayPalRequestData = array(
+		'URPPFields' => $URPPFields, 
+		'BillingAddress' => $BillingAddress, 
+		'ShippingAddress' => $ShippingAddress, 
+		'BillingPeriod' => $BillingPeriod, 
+		'CCDetails' => $CCDetails, 
+		'PayerInfo' => $PayerInfo
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->UpdateRecurringPaymentsProfile($PayPalRequestData);
+
+}
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index ca7dee9a..c1bc963e 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -1258,7 +1258,20 @@ public function UpdateSubscriptionProfile($DataArray) {
 
             $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId, 'PATCH', $patches);
 
-            if ($response['status_code'] === 201) {
+            if ( $response['status_code'] >= 200 && $response['status_code'] < 300 ) {
+
+                if($this->api_upgrade) {
+                    return [
+                        'success' => true,
+                        'status' => $response['body']['status'] ?? $response['status_code'],
+                        'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
+                        'ACK' => 'Success',
+                        'L_LONGMESSAGE0' => 'Patch Operations completed successfully which may not return a body',
+                        'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
+                        'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                    ];
+                }
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],

From 0cda7d7d0437c117b71acfbab281b4e6544f55f5 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 1 Dec 2025 12:20:59 +0530
Subject: [PATCH 055/146] Sample Methods in Templates

---
 templates/sample-methods/CancelInvoice.php    |  56 ++++
 .../sample-methods/CreateAndSendInvoice.php   | 243 ++++++++++++++++++
 templates/sample-methods/CreateInvoice.php    | 236 +++++++++++++++++
 .../CreateRecurringPaymentsProfile.php        | 143 +++++++++++
 templates/sample-methods/DeleteInvoice.php    |  45 ++++
 templates/sample-methods/DoDirectPayment.php  | 131 ++++++++++
 .../DoExpressCheckoutPayment.php              | 163 ++++++++++++
 templates/sample-methods/GetBalance.php       |  32 +++
 templates/sample-methods/GetPalDetails.php    |  28 ++
 .../sample-methods/GetPaymentOptions.php      |  40 +++
 .../GetRecurringPaymentsProfileDetails.php    |  44 ++++
 .../ManageRecurringPaymentsProfileStatus.php  |  50 ++++
 .../sample-methods/MarkInvoiceAsPaid.php      |  63 +++++
 .../sample-methods/MarkInvoiceAsRefunded.php  |  66 +++++
 templates/sample-methods/RemindInvoice.php    |  50 ++++
 templates/sample-methods/SearchInvoices.php   |  90 +++++++
 templates/sample-methods/SendInvoice.php      |  41 +++
 .../sample-methods/SetExpressCheckout.php     | 192 ++++++++++++++
 18 files changed, 1713 insertions(+)
 create mode 100644 templates/sample-methods/CancelInvoice.php
 create mode 100644 templates/sample-methods/CreateAndSendInvoice.php
 create mode 100644 templates/sample-methods/CreateInvoice.php
 create mode 100644 templates/sample-methods/CreateRecurringPaymentsProfile.php
 create mode 100644 templates/sample-methods/DeleteInvoice.php
 create mode 100644 templates/sample-methods/DoDirectPayment.php
 create mode 100644 templates/sample-methods/DoExpressCheckoutPayment.php
 create mode 100644 templates/sample-methods/GetBalance.php
 create mode 100644 templates/sample-methods/GetPalDetails.php
 create mode 100644 templates/sample-methods/GetPaymentOptions.php
 create mode 100644 templates/sample-methods/GetRecurringPaymentsProfileDetails.php
 create mode 100644 templates/sample-methods/ManageRecurringPaymentsProfileStatus.php
 create mode 100644 templates/sample-methods/MarkInvoiceAsPaid.php
 create mode 100644 templates/sample-methods/MarkInvoiceAsRefunded.php
 create mode 100644 templates/sample-methods/RemindInvoice.php
 create mode 100644 templates/sample-methods/SearchInvoices.php
 create mode 100644 templates/sample-methods/SendInvoice.php
 create mode 100644 templates/sample-methods/SetExpressCheckout.php

diff --git a/templates/sample-methods/CancelInvoice.php b/templates/sample-methods/CancelInvoice.php
new file mode 100644
index 00000000..de877b44
--- /dev/null
+++ b/templates/sample-methods/CancelInvoice.php
@@ -0,0 +1,56 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$CancelInvoiceFields = array(
+	'InvoiceID' => '', 		// ID of the invoice.
+	'Subject' => '', 		// Subject of the cancelation notification.
+	'NoteForPayer' => '', 		// Note to send the payer within the cancelation notification.
+	'SendCopyToMerchant' => ''	// Indicates whether to send a copy of the cancelation notification to the merchant.  Values are:  true/false
+);
+
+if( $api_mode === 'rest' ) {
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->CancelInvoice($CancelInvoiceFields);
+	
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+
+} else {
+	$PayPalRequestData = array('CancelInvoiceFields' => $CancelInvoiceFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->CancelInvoice($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic CancelInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); diff --git a/templates/sample-methods/CreateAndSendInvoice.php b/templates/sample-methods/CreateAndSendInvoice.php new file mode 100644 index 00000000..44f0b8b2 --- /dev/null +++ b/templates/sample-methods/CreateAndSendInvoice.php @@ -0,0 +1,243 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'rest' ) { + + $invoiceDetails = array( + "currency_code" => "", // The three-character ISO 4217 currency code. + "note" => "", // A note to the payer. + "term" => "", // The payment term of the invoice, such as DueOnReceipt, Net30, etc. + "memo" => "", // A memo for the invoice. + ); + + $nameData = array( + "given_name" => "", // The first name of the person. + "surname" => "" // The last name of the person. + ); + + $phonesData = array(); + + $phoneData = array( + "country_code" => "", // The country code of the phone number. + "national_number" => "", // The phone number without the country code. + "phone_type" => "" // The type of phone number. Valid Values: MOBILE, HOME, WORK, FAX. + ); + array_push($phonesData,$phoneData); + + $addressData = array( + "address_line_1" => "", // The first line of the address. + "admin_area_2" => "", // The city of the address. + "admin_area_1" => "", // The state of the address. + "postal_code" => "", // The postal code of the address. + "country_code" => "" // The country code of the address. + ); + + $InvoiceItems = array(); + + $InvoiceItem = array( + 'name' => '', // Required. SKU or name of the item. + 'description' => '', // Item description. + 'quantity' => '', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => '', // The currency code. + 'value' => '' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $InvoiceItem = array( + 'name' => '', // Required. SKU or name of the item. + 'description' => '', // Item description. + 'quantity' => '', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => '', // The currency code. + 'value' => '' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $configurationData = array( + "partial_payment" => array("allow_partial_payment" => false), // Indicates whether to allow partial payments. true or false. + "tax_calculated_after_discount" => '', // Indicates whether the tax amount is calculated after applying the discount. true or false. + "allow_tip" => '', // Indicates whether to allow the payer to add a tip to the invoice. true or false. + ); + + $PayPalRequestData = array( + "detail" => $invoiceDetails, + "invoicer" => array( + "name" => $nameData, + "email_address" => "", + "phones" => $phonesData, + "website" => "", + "address" => $addressData + ), + "primary_recipients" => array( + array( + "billing_info" => array( + "email_address" => "", + "name" => $nameData, + "address" => $addressData + ), + ) + ), + "items" => $InvoiceItems, + "configuration" => $configurationData + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->CreateAndSendInvoice($PayPalRequestData); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+
+} else {
+        // Prepare request arrays
+        $CreateInvoiceFields = array(
+                'MerchantEmail' => '', 				// Required.  Merchant email address.
+                'PayerEmail' => '', 							// Required.  Payer email address.
+                'Number' => '', 								// Unique ID for the invoice.
+                'CurrencyCode' => '', 								// Required.  Currency used for all invoice item amounts and totals.
+                'InvoiceDate' => '', 									// Date on which the invoice is enabled.
+                'DueDate' => '', 									// Date on which the invoice payment is due.
+                'PaymentTerms' => '', 							// Required.  Terms by which the invoice payment is due.  Values are:  DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45
+                'DiscountPercent' => '', 								// Discount percent applied to the invoice.
+                'DiscountAmount' => '', 								// Discount amount applied to the invoice.  If DiscountPercent is provided, DiscountAmount is ignored.
+                'Terms' => '', 										// General terms for the invoice.
+                'Note' => '', 							// Note to the payer company.
+                'MerchantMemo' => '', 						// Memo for bookkeeping that is private to the merchant.
+                'ShippingAmount' => '', 								// Cost of shipping
+                'ShippingTaxName' => '', 								// Name of the applicable tax on the shipping cost.
+                'ShippingTaxRate' => '', 								// Rate of the applicable tax on the shipping cost.
+                'LogoURL' => ''                 	// Complete URL to an external image used as the logo, if any.
+        );
+                                                                
+        $BusinessInfo = array(
+                'FirstName' => '', 			// First name of the company contact.
+                'LastName' => '', 			// Last name of the company contact.
+                'BusinessName' => '', 		// Company business name.
+                'Phone' => '', 			// Phone number for contacting the company.
+                'Fax' => '', 			// Fax number used by the company.
+                'Website' => '', 		// Website used by the company.
+                'Custom' => '' 		// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $BusinessInfoAddress = array(
+                'Line1' => '', 		// Required. First line of address.
+                'Line2' => '', 				// Second line of address.
+                'City' => '', 			// Required. City of the address.
+                'State' => '', 			// State for the address.
+                'PostalCode' => '', 		// Postal code of the address
+                'CountryCode' => ''			// Required.  Country code of the address.
+        );
+
+        $BillingInfo = array(
+                'FirstName' => '', 		// First name of the company contact.
+                'LastName' => '', 		// Last name of the company contact.
+                'BusinessName' => '', 		// Company business name.
+                'Phone' => '', 			// Phone number for contacting the company.
+                'Fax' => '', 			// Fax number used by the company.
+                'Website' => '', 		// Website used by the company.
+                'Custom' => '' 			// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $BillingInfoAddress = array(
+                'Line1' => '', 			// Required. First line of address.
+                'Line2' => '', 			// Second line of address.
+                'City' => '', 			// Required. City of the address.
+                'State' => '', 			// State for the address.
+                'PostalCode' => '', 		// Postal code of the address
+                'CountryCode' => ''		// Required.  Country code of the address.
+        );
+
+        $ShippingInfo = array(
+                'FirstName' => '', 		// First name of the company contact.
+                'LastName' => '', 		// Last name of the company contact.
+                'BusinessName' => '', 		// Company business name.
+                'Phone' => '', 			// Phone number for contacting the company.
+                'Fax' => '', 			// Fax number used by the company.
+                'Website' => '', 		// Website used by the company.
+                'Custom' => '' 			// Custom value to be displayed in the contact information details.
+        );
+                                                
+        $ShippingInfoAddress = array(
+                'Line1' => '', 			// Required. First line of address.
+                'Line2' => '', 			// Second line of address.
+                'City' => '', 			// Required. City of the address.
+                'State' => '', 			// State for the address.
+                'PostalCode' => '', 		// Postal code of the address
+                'CountryCode' => ''		// Required.  Country code of the address.
+        );
+
+        // For invoice items you populate a nested array with multiple $InvoiceItem arrays.  Normally you'll be looping through cart items to populate the $InvoiceItem 
+        // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems.
+
+        $InvoiceItems = array();
+
+        $InvoiceItem = array(
+                'Name' => '', 				// Required.  SKU or name of the item.
+                'Description' => '', 		// Item description.
+                'Date' => '', 				// Date on which the product or service was provided.
+                'Quantity' => '', 					// Required.  Item count.  Values are:  0 to 10000
+                'UnitPrice' => '', 				// Required.  Price of the item, in the currency specified by the invoice.
+                'TaxName' => '', 					// Name of the applicable tax.
+                'TaxRate' => ''						// Rate of the applicable tax.
+        );
+        array_push($InvoiceItems,$InvoiceItem);
+
+        $InvoiceItem = array(
+                'Name' => '', 				// Required.  SKU or name of the item.
+                'Description' => '', 		// Item description.
+                'Date' => '', 				// Date on which the product or service was provided.
+                'Quantity' => '', 					// Required.  Item count.  Values are:  0 to 10000
+                'UnitPrice' => '', 				// Required.  Price of the item, in the currency specified by the invoice.
+                'TaxName' => '', 					// Name of the applicable tax.
+                'TaxRate' => ''						// Rate of the applicable tax.
+        );
+        array_push($InvoiceItems,$InvoiceItem);
+
+        $PayPalRequestData = array(
+                'CreateInvoiceFields' => $CreateInvoiceFields, 
+                'BusinessInfo' => $BusinessInfo, 
+                //'BusinessInfoAddress' => $BusinessInfoAddress, 
+                //'BillingInfo' => $BillingInfo, 
+                //'BillingInfoAddress' => $BillingInfoAddress, 
+                //'ShippingInfo' => $ShippingInfo, 
+                //'ShippingInfoAddress' => $ShippingInfoAddress, 
+                'InvoiceItems' => $InvoiceItems
+        );
+
+        // Pass data into class for processing with PayPal and load the response array into $PayPalResult
+        $PayPalResult = $PayPal->Adaptive->CreateAndSendInvoice($PayPalRequestData);
+
+        // Write the contents of the response array to the screen for demo purposes.
+        echo '
';
+        echo "

Deprecated Notice: The classic CreateAndSendInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + + +print_r($PayPalResult); diff --git a/templates/sample-methods/CreateInvoice.php b/templates/sample-methods/CreateInvoice.php new file mode 100644 index 00000000..0fdaa0e7 --- /dev/null +++ b/templates/sample-methods/CreateInvoice.php @@ -0,0 +1,236 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'classic' ){ + + // Prepare request arrays + $CreateInvoiceFields = array( + 'MerchantEmail' => '', // Required. Merchant email address. + 'PayerEmail' => '', // Required. Payer email address. + 'Number' => '', // Unique ID for the invoice. + 'CurrencyCode' => '', // Required. Currency used for all invoice item amounts and totals. + 'InvoiceDate' => '', // Date on which the invoice is enabled. + 'DueDate' => '', // Date on which the invoice payment is due. + 'PaymentTerms' => '', // Required. Terms by which the invoice payment is due. Values are: DueOnReceipt, DueOnSpecified, Net10, Net15, Net30, Net45 + 'DiscountPercent' => '', // Discount percent applied to the invoice. + 'DiscountAmount' => '', // Discount amount applied to the invoice. If DiscountPercent is provided, DiscountAmount is ignored. + 'Terms' => '', // General terms for the invoice. + 'Note' => '', // Note to the payer company. + 'MerchantMemo' => '', // Memo for bookkeeping that is private to the merchant. + 'ShippingAmount' => '', // Cost of shipping + 'ShippingTaxName' => '', // Name of the applicable tax on the shipping cost. + 'ShippingTaxRate' => '', // Rate of the applicable tax on the shipping cost. + 'LogoURL' => '' // Complete URL to an external image used as the logo, if any. + ); + + $BusinessInfo = array( + 'FirstName' => '', // First name of the company contact. + 'LastName' => '', // Last name of the company contact. + 'BusinessName' => '', // Company business name. + 'Phone' => '', // Phone number for contacting the company. + 'Fax' => '', // Fax number used by the company. + 'Website' => '', // Website used by the company. + 'Custom' => '' // Custom value to be displayed in the contact information details. + ); + + $BusinessInfoAddress = array( + 'Line1' => '', // Required. First line of address. + 'Line2' => '', // Second line of address. + 'City' => '', // Required. City of the address. + 'State' => '', // State for the address. + 'PostalCode' => '', // Postal code of the address + 'CountryCode' => '' // Required. Country code of the address. + ); + + $BillingInfo = array( + 'FirstName' => '', // First name of the company contact. + 'LastName' => '', // Last name of the company contact. + 'BusinessName' => '', // Company business name. + 'Phone' => '', // Phone number for contacting the company. + 'Fax' => '', // Fax number used by the company. + 'Website' => '', // Website used by the company. + 'Custom' => '' // Custom value to be displayed in the contact information details. + ); + + $BillingInfoAddress = array( + 'Line1' => '', // Required. First line of address. + 'Line2' => '', // Second line of address. + 'City' => '', // Required. City of the address. + 'State' => '', // State for the address. + 'PostalCode' => '', // Postal code of the address + 'CountryCode' => '' // Required. Country code of the address. + ); + + $ShippingInfo = array( + 'FirstName' => '', // First name of the company contact. + 'LastName' => '', // Last name of the company contact. + 'BusinessName' => '', // Company business name. + 'Phone' => '', // Phone number for contacting the company. + 'Fax' => '', // Fax number used by the company. + 'Website' => '', // Website used by the company. + 'Custom' => '' // Custom value to be displayed in the contact information details. + ); + + $ShippingInfoAddress = array( + 'Line1' => '', // Required. First line of address. + 'Line2' => '', // Second line of address. + 'City' => '', // Required. City of the address. + 'State' => '', // State for the address. + 'PostalCode' => '', // Postal code of the address + 'CountryCode' => '' // Required. Country code of the address. + ); + + // For invoice items you populate a nested array with multiple $InvoiceItem arrays. Normally you'll be looping through cart items to populate the $InvoiceItem + // array and then push it into the $InvoiceItems array at the end of each loop for an entire collection of all items in $InvoiceItems. + + $InvoiceItems = array(); + + $InvoiceItem = array( + 'Name' => '', // Required. SKU or name of the item. + 'Description' => '', // Item description. + 'Date' => '', // Date on which the product or service was provided. + 'Quantity' => '', // Required. Item count. Values are: 0 to 10000 + 'UnitPrice' => '', // Required. Price of the item, in the currency specified by the invoice. + 'TaxName' => '', // Name of the applicable tax. + 'TaxRate' => '' // Rate of the applicable tax. + ); + array_push($InvoiceItems,$InvoiceItem); + + $InvoiceItem = array( + 'Name' => '', // Required. SKU or name of the item. + 'Description' => '', // Item description. + 'Date' => '', // Date on which the product or service was provided. + 'Quantity' => '', // Required. Item count. Values are: 0 to 10000 + 'UnitPrice' => '', // Required. Price of the item, in the currency specified by the invoice. + 'TaxName' => '', // Name of the applicable tax. + 'TaxRate' => '' // Rate of the applicable tax. + ); + array_push($InvoiceItems,$InvoiceItem); + + $PayPalRequestData = array( + 'CreateInvoiceFields' => $CreateInvoiceFields, + 'BusinessInfo' => $BusinessInfo, + 'BusinessInfoAddress' => $BusinessInfoAddress, + 'BillingInfo' => $BillingInfo, + 'BillingInfoAddress' => $BillingInfoAddress, + 'ShippingInfo' => $ShippingInfo, + 'ShippingInfoAddress' => $ShippingInfoAddress, + 'InvoiceItems' => $InvoiceItems + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->Adaptive->CreateInvoice($PayPalRequestData); + echo '
';
+        echo "

Deprecated Notice: The classic CreateInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} else { + $invoiceDetails = array( + "currency_code" => "", // The three-character ISO 4217 currency code. + "note" => "", // A note to the payer. + "term" => "", // The payment term of the invoice, such as DueOnReceipt, Net30, etc. + "memo" => "", // A memo for the invoice. + ); + + $nameData = array( + "given_name" => "", // The first name of the person. + "surname" => "" // The last name of the person. + ); + + $phonesData = array(); + + $phoneData = array( + "country_code" => "", // The country code of the phone number. + "national_number" => "", // The phone number without the country code. + "phone_type" => "" // The type of phone number. Valid Values: MOBILE, HOME, WORK, FAX. + ); + array_push($phonesData,$phoneData); + + $addressData = array( + "address_line_1" => "", // The first line of the address. + "admin_area_2" => "", // The city of the address. + "admin_area_1" => "", // The state of the address. + "postal_code" => "", // The postal code of the address. + "country_code" => "" // The country code of the address. + ); + + $InvoiceItems = array(); + + $InvoiceItem = array( + 'name' => '', // Required. SKU or name of the item. + 'description' => '', // Item description. + 'quantity' => '', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => '', // The currency code. + 'value' => '' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $InvoiceItem = array( + 'name' => '', // Required. SKU or name of the item. + 'description' => '', // Item description. + 'quantity' => '', // Required. Item count. Values are: 0 to 10000 + 'unit_amount' => array( + 'currency_code' => '', // The currency code. + 'value' => '' // The amount for the item. + ), + ); + array_push($InvoiceItems,$InvoiceItem); + + $configurationData = array( + "partial_payment" => array("allow_partial_payment" => false), // Indicates whether to allow partial payments. true or false. + "tax_calculated_after_discount" => '', // Indicates whether the tax amount is calculated after applying the discount. true or false. + "allow_tip" => '', // Indicates whether to allow the payer to add a tip to the invoice. true or false. + ); + + $PayPalRequestData = array( + "detail" => $invoiceDetails, + "invoicer" => array( + "name" => $nameData, + "email_address" => "", + "phones" => $phonesData, + "website" => "", + "address" => $addressData + ), + "primary_recipients" => array( + array( + "billing_info" => array( + "email_address" => "", + "name" => $nameData, + "address" => $addressData + ), + ) + ), + "items" => $InvoiceItems, + "configuration" => $configurationData + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->CreateInvoice($PayPalRequestData); + echo '
';
+}
+print_r($PayPalResult);
diff --git a/templates/sample-methods/CreateRecurringPaymentsProfile.php b/templates/sample-methods/CreateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..97815082
--- /dev/null
+++ b/templates/sample-methods/CreateRecurringPaymentsProfile.php
@@ -0,0 +1,143 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+    'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$CRPPFields = array(
+	'token' => '', 		// Token returned from PayPal SetExpressCheckout.  Can also use token returned from SetCustomerBillingAgreement.
+);
+				
+$DaysTimestamp = strtotime('now');
+$Mo = date('m', $DaysTimestamp);
+$Day = date('d', $DaysTimestamp);
+$Year = date('Y', $DaysTimestamp);
+$StartDateGMT = $Year . '-' . $Mo . '-' . $Day . 'T00:00:00\Z';
+				
+$ProfileDetails = array(
+	'subscribername' => '', 					// Full name of the person receiving the product or service paid for by the recurring payment.  32 char max.
+	'profilestartdate' => $StartDateGMT, 					// Required.  The date when the billing for this profile begins.  Must be a valid date in UTC/GMT format.
+	'profilereference' => '' 					// The merchant's own unique invoice number or reference ID.  127 char max.
+);
+				
+$ScheduleDetails = array(
+	'desc' => '', 		// Required.  Description of the recurring payment.  This field must match the corresponding billing agreement description included in SetExpressCheckout.
+	'maxfailedpayments' => '', 			// The number of scheduled payment periods that can fail before the profile is automatically suspended.  
+	'autobillamt' => '1' 				// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.  Values can be: NoAutoBill or AddToNextBilling
+);
+				
+$BillingPeriod = array(
+	'trialbillingperiod' => '', 
+	'trialbillingfrequency' => '', 
+	'trialtotalbillingcycles' => '', 
+	'trialamt' => '', 
+	'billingperiod' => '', 		// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+	'billingfrequency' => '', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+	'totalbillingcycles' => '', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+	'amt' => '', 			// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+	'currencycode' => '', 		// Required.  Three-letter currency code.
+	'shippingamt' => '', 			// Shipping amount for each billing cycle during the payment period.
+	'taxamt' => '' 				// Tax amount for each billing cycle during the payment period.
+);
+				
+$ActivationDetails = array(
+	'initamt' => '', 			// Initial non-recurring payment amount due immediatly upon profile creation.  Use an initial amount for enrolment or set-up fees.
+	'failedinitamtaction' => '', 		// By default, PayPal will suspend the pending profile in the event that the initial payment fails.  You can override this.  Values are: ContinueOnFailure or CancelOnFailure
+);
+				
+$CCDetails = array(
+	'creditcardtype' => '', 		// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+	'acct' => '', 		// Required.  Credit card number.  No spaces or punctuation.  
+	'expdate' => '', 			// Required.  Credit card expiration date.  Format is MMYYYY
+	'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+	'startdate' => '', 			// Month and year that Maestro or Solo card was issued.  MMYYYY
+	'issuenumber' => ''			// Issue number of Maestro or Solo card.  Two numeric digits max.
+);
+				
+$PayerInfo = array(
+	'email' => '', 		// Email address of payer.
+	'payerid' => '', 			// Unique PayPal customer ID for payer.
+	'payerstatus' => '', 			// Status of payer.  Values are verified or unverified
+	'countrycode' => '', 			// Payer's country of residence in the form of the two letter code.
+	'business' => '' 		// Payer's business name.
+);
+				
+$PayerName = array(
+	'salutation' => '', 			// Payer's salutation.  20 char max.
+	'firstname' => '', 		// Payer's first name.  25 char max.
+	'middlename' => '', 			// Payer's middle name.  25 char max.
+	'lastname' => '', 		// Payer's last name.  25 char max.
+	'suffix' => ''				// Payer's suffix.  12 char max.
+);
+				
+$BillingAddress = array(
+	'street' => '', 		// Required.  First street address.
+	'street2' => '', 			// Second street address.
+	'city' => '', 			// Required.  Name of City.
+	'state' => '', 			// Required. Name of State or Province.
+	'countrycode' => '', 			// Required.  Country code.
+	'zip' => '', 			// Required.  Postal code of payer.
+	'phonenum' => '' 			// Phone Number of payer.  20 char max.
+);
+					
+$ShippingAddress = array(
+	'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 		// Second street address.  100 char max.
+	'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountrycode' => '', 	// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+);
+						
+$PayPalRequestData = array(
+	'ProfileDetails' => $ProfileDetails, 
+	'ScheduleDetails' => $ScheduleDetails, 
+	'BillingPeriod' => $BillingPeriod, 
+	'CCDetails' => $CCDetails, 
+	'PayerInfo' => $PayerInfo, 
+	'PayerName' => $PayerName, 
+	'BillingAddress' => $BillingAddress
+);
+if( $api_mode == 'rest' ) {
+    $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($domain);
+
+    if ($PayPalResult['success']) {
+        $approve_url = '';
+        if (!empty($PayPalResult['response']['links'])) {
+            foreach ($PayPalResult['response']['links'] as $link) {
+                if (isset($link['rel']) && $link['rel'] === 'approve') {
+                    $approve_url = $link['href'];
+                    break;
+                }
+            }
+        }
+        echo 'Click here to continue.

'; + + echo '
';
+        print_r($PayPalResult);
+    }
+} else {
+    $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($PayPalRequestData);
+
+    echo '
';
+    echo "

Deprecated Notice: The classic CreateRecurringPaymentsProfile method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + print_r($PayPalResult); + +} + diff --git a/templates/sample-methods/DeleteInvoice.php b/templates/sample-methods/DeleteInvoice.php new file mode 100644 index 00000000..49733d4f --- /dev/null +++ b/templates/sample-methods/DeleteInvoice.php @@ -0,0 +1,45 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$InvoiceID = ''; + +if( $api_mode === 'rest' ) { + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->DeleteInvoice($InvoiceID); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+} else {
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->DeleteInvoice($InvoiceID);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic DeleteInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} +print_r($PayPalResult); diff --git a/templates/sample-methods/DoDirectPayment.php b/templates/sample-methods/DoDirectPayment.php new file mode 100644 index 00000000..15793048 --- /dev/null +++ b/templates/sample-methods/DoDirectPayment.php @@ -0,0 +1,131 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$DPFields = array( + 'paymentaction' => '', // How you want to obtain payment. Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture. Sale indicates that this is a final sale for which you are requesting payment. Default is Sale. + 'ipaddress' => '', // Required. IP address of the payer's browser. + 'returnfmfdetails' => '' // Flag to determine whether you want the results returned by FMF. 1 or 0. Default is 0. +); + +$CCDetails = array( + 'creditcardtype' => '', // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. + 'acct' => '', // Required. Credit card number. No spaces or punctuation. + 'expdate' => '', // Required. Credit card expiration date. Format is MMYYYY + 'cvv2' => '', // Requirements determined by your PayPal account settings. Security digits for credit card. + 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY + 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. +); + +$PayerInfo = array( + 'email' => '', // Email address of payer. + 'payerid' => '', // Unique PayPal customer ID for payer. + 'payerstatus' => '', // Status of payer. Values are verified or unverified + 'business' => '' // Payer's business name. +); + +$PayerName = array( + 'salutation' => '', // Payer's salutation. 20 char max. + 'firstname' => '', // Payer's first name. 25 char max. + 'middlename' => '', // Payer's middle name. 25 char max. + 'lastname' => '', // Payer's last name. 25 char max. + 'suffix' => '' // Payer's suffix. 12 char max. +); + +$BillingAddress = array( + 'street' => '', // Required. First street address. + 'street2' => '', // Second street address. + 'city' => '', // Required. Name of City. + 'state' => '', // Required. Name of State or Province. + 'countrycode' => '', // Required. Country code. + 'zip' => '', // Required. Postal code of payer. + 'phonenum' => '' // Phone Number of payer. 20 char max. +); + +$ShippingAddress = array( + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountrycode' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '' // Phone number for shipping address. 20 char max. +); + +$PaymentDetails = array( + 'amt' => '', // Required. Total amount of order, including shipping, handling, and tax. + 'currencycode' => '', // Required. Three-letter currency code. Default is USD. + 'itemamt' => '', // Required if you include itemized cart details. (L_AMTn, etc.) Subtotal of items not including S&H, or tax. + 'shippingamt' => '', // Total shipping costs for the order. If you specify shippingamt, you must also specify itemamt. + 'handlingamt' => '', // Total handling costs for the order. If you specify handlingamt, you must also specify itemamt. + 'taxamt' => '', // Required if you specify itemized cart tax details. Sum of tax for all items on the order. Total sales tax. + 'desc' => '', // Description of the order the customer is purchasing. 127 char max. + 'custom' => '', // Free-form field for your own use. 256 char max. + 'invnum' => '', // Your own invoice or tracking number + 'buttonsource' => '', // An ID code for use by 3rd party apps to identify transactions. + 'notifyurl' => '' // URL for receiving Instant Payment Notifications. This overrides what your profile is set to use. +); + +$OrderItems = array(); +$Item = array( + 'l_name' => '', // Item Name. 127 char max. + 'l_desc' => '', // Item description. 127 char max. + 'l_amt' => '', // Cost of individual item. + 'l_number' => '', // Item Number. 127 char max. + 'l_qty' => '', // Item quantity. Must be any positive integer. + 'l_taxamt' => '', // Item's sales tax amount. + 'l_ebayitemnumber' => '', // eBay auction number of item. + 'l_ebayitemauctiontxnid' => '', // eBay transaction ID of purchased item. + 'l_ebayitemorderid' => '' // eBay order ID for the item. +); +array_push($OrderItems, $Item); + +$Item = array( + 'l_name' => '', // Item Name. 127 char max. + 'l_desc' => '', // Item description. 127 char max. + 'l_amt' => '', // Cost of individual item. + 'l_number' => '', // Item Number. 127 char max. + 'l_qty' => '', // Item quantity. Must be any positive integer. + 'l_taxamt' => '', // Item's sales tax amount. + 'l_ebayitemnumber' => '', // eBay auction number of item. + 'l_ebayitemauctiontxnid' => '', // eBay transaction ID of purchased item. + 'l_ebayitemorderid' => '' // eBay order ID for the item. +); +array_push($OrderItems, $Item); + +$PayPalRequestData = array( + 'DPFields' => $DPFields, + 'CCDetails' => $CCDetails, + 'PayerInfo' => $PayerInfo, + 'PayerName' => $PayerName, + 'BillingAddress' => $BillingAddress, + 'PaymentDetails' => $PaymentDetails, + 'OrderItems' => $OrderItems +); + +$PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData); + +if( $api_mode === 'rest' ){ + $_SESSION['transaction_id'] = isset($PayPalResult['RESPONSE']['id']) ? $PayPalResult['RESPONSE']['id'] : ''; +} else { + $_SESSION['transaction_id'] = isset($PayPalResult['TRANSACTIONID']) ? $PayPalResult['TRANSACTIONID'] : ''; +} +echo '
';
+print_r($PayPalResult);
diff --git a/templates/sample-methods/DoExpressCheckoutPayment.php b/templates/sample-methods/DoExpressCheckoutPayment.php
new file mode 100644
index 00000000..a0569f70
--- /dev/null
+++ b/templates/sample-methods/DoExpressCheckoutPayment.php
@@ -0,0 +1,163 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+        'PayPalAPIUpgrade' => $api_upgrade,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+$orderId = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+	$orderId = $_SESSION['SetExpressCheckoutResult']['order_id'];
+} else {
+	$orderId = $_SESSION['SetExpressCheckoutResult']['TOKEN'];
+}
+
+$payerID = '';
+
+$DECPFields = array(
+	'token' => $orderId, 	// Required.  A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+	'payerid' => $payerID, 				// Required.  Unique PayPal customer id of the payer.  Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL.
+	'returnfmfdetails' => '1', 					// Flag to indicate whether you want the results returned by Fraud Management Filters or not.  1 or 0.
+	'giftmessage' => '', 						// The gift message entered by the buyer on the PayPal Review page.  150 char max.
+	'giftreceiptenable' => '', 					// Pass true if a gift receipt was selected by the buyer on the PayPal Review page. Otherwise pass false.
+	'giftwrapname' => '', 						// The gift wrap name only if the gift option on the PayPal Review page was selected by the buyer.
+	'giftwrapamount' => '', 					// The amount only if the gift option on the PayPal Review page was selected by the buyer.
+	'buyermarketingemail' => '', 					// The buyer email address opted in by the buyer on the PayPal Review page.
+	'surveyquestion' => '', 					// The survey question on the PayPal Review page.  50 char max.
+	'surveychoiceselected' => '',  					// The survey response selected by the buyer on the PayPal Review page.  15 char max.
+	'allowedpaymentmethod' => '', 					// The payment method type. Specify the value InstantPaymentOnly.
+	'buttonsource' => '' 						// ID code for use by third-party apps to identify transactions in PayPal. 
+);
+						
+$Payments = array();
+$Payment = array(
+	'amt' => '100.00', 								// Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+	'currencycode' => 'USD', 							// A three-character currency code.  Default is USD.
+	'itemamt' => '80.00', 								// Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.  
+	'shippingamt' => '15.00', 							// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+	'insuranceoptionoffered' => '', 						// If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount.  If true, the total shipping insurance for this order must be a positive number.
+	'handlingamt' => '', 								// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+	'taxamt' => '5.00', 								// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order. 
+	'desc' => 'This is a test order.', 						// Description of items on the order.  127 char max.
+	'custom' => '', 								// Free-form field for your own use.  256 char max.
+	'invnum' => '', 								// Your own invoice or tracking number.  127 char max.
+	'notifyurl' => '',  								// URL for receiving Instant Payment Notifications
+	'shiptoname' => '', 								// Required if shipping is included.  Person's name associated with this address.  32 char max.
+	'shiptostreet' => '', 								// Required if shipping is included.  First street address.  100 char max.
+	'shiptostreet2' => '', 								// Second street address.  100 char max.
+	'shiptocity' => '', 								// Required if shipping is included.  Name of city.  40 char max.
+	'shiptostate' => '', 								// Required if shipping is included.  Name of state or province.  40 char max.
+	'shiptozip' => '', 								// Required if shipping is included.  Postal code of shipping address.  20 char max.
+	'shiptocountry' => '', 								// Required if shipping is included.  Country code of shipping address.  2 char max.
+	'shiptophonenum' => '',  							// Phone number for shipping address.  20 char max.
+	'notetext' => 'This is a test note before ever having left the web site.', 	// Note to the merchant.  255 char max.  
+	'allowedpaymentmethod' => '', 							// The payment method type.  Specify the value InstantPaymentOnly.
+	'paymentaction' => 'Sale', 							// How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order. 
+	'paymentrequestid' => '',  							// A unique identifier of the specific payment request, which is required for parallel payments. 
+	'sellerpaypalaccountid' => ''							// A unique identifier for the merchant.  For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant.
+);
+				
+$PaymentOrderItems = array();
+$Item = array(
+	'name' => 'Widget 123', 					// Item name. 127 char max.
+	'desc' => 'Widget 123', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '123', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/123.php', 	// URL for the item.
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Item = array(
+	'name' => 'Widget 456', 					// Item name. 127 char max.
+	'desc' => 'Widget 456', 					// Item description. 127 char max.
+	'amt' => '40.00', 						// Cost of item.
+	'number' => '456', 						// Item number.  127 char max.
+	'qty' => '1', 							// Item qty on order.  Any positive integer.
+	'taxamt' => '', 						// Item sales tax
+	'itemurl' => 'http://www.angelleye.com/products/456.php', 	// URL for the item.
+	'itemweightvalue' => '', 					// The weight value of the item.
+	'itemweightunit' => '', 					// The weight unit of the item.
+	'itemheightvalue' => '', 					// The height value of the item.
+	'itemheightunit' => '', 					// The height unit of the item.
+	'itemwidthvalue' => '', 					// The width value of the item.
+	'itemwidthunit' => '', 						// The width unit of the item.
+	'itemlengthvalue' => '', 					// The length value of the item.
+	'itemlengthunit' => '',  					// The length unit of the item.
+	'ebayitemnumber' => '', 					// Auction item number.  
+	'ebayitemauctiontxnid' => '', 					// Auction transaction ID number.  
+	'ebayitemorderid' => '',  					// Auction order ID number.
+	'ebayitemcartid' => ''						// The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters
+);
+array_push($PaymentOrderItems, $Item);
+
+$Payment['order_items'] = $PaymentOrderItems;
+array_push($Payments, $Payment);				
+
+$UserSelectedOptions = array(
+	'shippingcalculationmode' => '', 	// Describes how the options that were presented to the user were determined.  values are:  API - Callback   or   API - Flatrate.
+	'insuranceoptionselected' => '', 	// The Yes/No option that you chose for insurance.
+	'shippingoptionisdefault' => '', 	// Is true if the buyer chose the default shipping option.  
+	'shippingoptionamount' => '', 		// The shipping amount that was chosen by the buyer.
+	'shippingoptionname' => '', 		// Is true if the buyer chose the default shipping option...??  Maybe this is supposed to show the name..??
+);
+
+$GetExpressCheckoutRequest = array(
+	'DECPFields' => $DECPFields, 
+	'Payments' => $Payments
+);
+
+/*
+ * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal
+ */
+if ( $api_mode === 'rest' ) {
+        $GECDResult = $PayPal->GetExpressCheckoutDetails($GetExpressCheckoutRequest);
+} else {
+        $GECDResult = $PayPal->GetExpressCheckoutDetails($orderId);
+}
+echo 'GetExpressCheckoutDetails
';
+print_r($GECDResult);
+echo '

'; + +if ( $api_mode === 'rest' && ! $api_upgrade ) { + $payerID = isset($GECDResult['order']['payer']['payer_id']) ? $GECDResult['order']['payer']['payer_id'] : ''; +} else { + $payerID = $GECDResult['PAYERID']; +} + +$DECPFields['payerid'] = $payerID; + +$PayPalRequest = array( + 'DECPFields' => $DECPFields, + 'Payments' => $Payments +); + +$_SESSION['PayPalResult'] = $PayPal->DoExpressCheckoutPayment($PayPalRequest); +echo 'DoExpressCheckout
';
+print_r($_SESSION['PayPalResult']);
diff --git a/templates/sample-methods/GetBalance.php b/templates/sample-methods/GetBalance.php
new file mode 100644
index 00000000..4090ce69
--- /dev/null
+++ b/templates/sample-methods/GetBalance.php
@@ -0,0 +1,32 @@
+ $sandbox,
+        'PayPalAPIMode' => $api_mode,
+        'PayPalAPIUpgrade' => $api_upgrade,
+        'APIUsername' => $api_username,
+        'APIPassword' => $api_password,
+        'APISignature' => $api_signature,
+        'ClientID' => $rest_client_id,
+        'ClientSecret' => $rest_client_secret,
+        'PrintHeaders' => $print_headers,
+        'LogResults' => $log_results,
+        'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Prepare request arrays
+$GBFields = array('returnallcurrencies' => true);
+$PayPalRequestData = array('GBFields'=>$GBFields);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetBalance($PayPalRequestData);
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/sample-methods/GetPalDetails.php b/templates/sample-methods/GetPalDetails.php
new file mode 100644
index 00000000..8c389dbb
--- /dev/null
+++ b/templates/sample-methods/GetPalDetails.php
@@ -0,0 +1,28 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+    'PayPalAPIUpgrade' => $api_upgrade,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret, 
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayPalResult = $PayPal->GetPalDetails();
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/templates/sample-methods/GetPaymentOptions.php b/templates/sample-methods/GetPaymentOptions.php
new file mode 100644
index 00000000..ef4398b8
--- /dev/null
+++ b/templates/sample-methods/GetPaymentOptions.php
@@ -0,0 +1,40 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$PayKey = '';
+if( $api_mode === 'rest' ){
+	$PayPalResult = $PayPal->getOrder($PayKey);
+	echo '
';
+} else {
+	$PayPalResult = $PayPal->Adaptive->GetPaymentOptions($PayKey);
+	echo '
';
+	echo "

Deprecated Notice: The classic GetPaymentOptions method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); \ No newline at end of file diff --git a/templates/sample-methods/GetRecurringPaymentsProfileDetails.php b/templates/sample-methods/GetRecurringPaymentsProfileDetails.php new file mode 100644 index 00000000..0751ee83 --- /dev/null +++ b/templates/sample-methods/GetRecurringPaymentsProfileDetails.php @@ -0,0 +1,44 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +if( $api_mode === 'classic' ) { + // Prepare request arrays + $GRPPDFields = array( + 'profileid' => '' // Profile ID of the profile you want to get details for. + ); + + $PayPalRequestData = array('GRPPDFields'=>$GRPPDFields); +} else{ + $PayPalRequestData = array( + 'token' => '', + 'ba_token' => '', + 'subscription_id' => '', + ); +} + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$PayPalResult = $PayPal->GetRecurringPaymentsProfileDetails($PayPalRequestData); + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
diff --git a/templates/sample-methods/ManageRecurringPaymentsProfileStatus.php b/templates/sample-methods/ManageRecurringPaymentsProfileStatus.php
new file mode 100644
index 00000000..c9223edf
--- /dev/null
+++ b/templates/sample-methods/ManageRecurringPaymentsProfileStatus.php
@@ -0,0 +1,50 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+	'PayPalAPIUpgrade' => $api_upgrade,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+
+if($api_mode === 'rest'){
+	$PayPalRequestData = array(
+			'subscription_id' => '',
+			'subscription_action' => '',                      // Action to be performed on the subscription.  Must be: cancel, suspend, activate
+			'subscription_reason' => ''          // Reason for the change in status
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->ManageRecurringPaymentsProfileStatus($PayPalRequestData);
+
+} else {
+	// Prepare request arrays
+	$MRPPSFields = array(
+		'profileid' => '', 		// Required. Recurring payments profile ID returned from CreateRecurring...
+		'action' => '', 			// Required. The action to be performed.  Mest be: Cancel, Suspend, Reactivate
+		'note' => ''					// The reason for the change in status.  For express checkout the message will be included in email to buyers.  Can also be seen in both accounts in the status history.
+	);
+						
+	$PayPalRequestData = array('MRPPSFields'=>$MRPPSFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->ManageRecurringPaymentsProfileStatus($PayPalRequestData);	
+}
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);
diff --git a/templates/sample-methods/MarkInvoiceAsPaid.php b/templates/sample-methods/MarkInvoiceAsPaid.php
new file mode 100644
index 00000000..0f3362e6
--- /dev/null
+++ b/templates/sample-methods/MarkInvoiceAsPaid.php
@@ -0,0 +1,63 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+if( $api_mode === 'rest' ) {
+
+		// Prepare request arrays
+		$MarkInvoiceAsPaidFields = array(
+			'type' => '', 		                // Required.  ID of the invoice to mark paid.
+			'method' => '', 				// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+			'note' => '', 		// Optional note associated with the payment.
+			'date' => '',
+			'InvoiceID' => '',
+		);
+
+		$PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields);
+		$PayPalResult = $PayPal->MarkInvoiceAsPaid($PayPalRequestData);	
+		echo '
';	
+} else {
+	// Prepare request arrays
+	$MarkInvoiceAsPaidFields = array(
+		'InvoiceID' => '', 		// Required.  ID of the invoice to mark paid.
+		'Method' => '', 					// Method t hat can be used to mark an invoice as paid when the payer p ays offline.  Values are:  BankTransfer, Cash, Check, CreditCard, DebitCard, Other, PayPal, WireTransfer
+		'Note' => '', 			// Optional note associated with the payment.
+		'Date' => ''					// Date the invoice was paid.
+	);
+
+	$PayPalRequestData = array('MarkInvoiceAsPaidFields' => $MarkInvoiceAsPaidFields);
+	$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsPaid($PayPalRequestData);
+	echo '
';
+	echo "

Deprecated Notice: The classic MarkInvoiceAsPaid method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +// Write the contents of the response array to the screen for demo purposes. +print_r($PayPalResult); + + + + diff --git a/templates/sample-methods/MarkInvoiceAsRefunded.php b/templates/sample-methods/MarkInvoiceAsRefunded.php new file mode 100644 index 00000000..8a46957e --- /dev/null +++ b/templates/sample-methods/MarkInvoiceAsRefunded.php @@ -0,0 +1,66 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'rest' ) { + // Prepare request arrays + $MarkInvoiceAsRefundedFields = array( + 'note' => '', + 'amount' => array( + 'currency_code' => '', + 'value' => '' + ), + 'method' => '', + 'Date' => '' + ); + + $PayPalRequestData = array( + 'InvoiceID' => '', // Invoice ID of the invoice to mark refunded which has been paid + 'MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->MarkInvoiceAsRefunded($PayPalRequestData); + echo '
';
+} else {
+	// Prepare request arrays
+	$MarkInvoiceAsRefundedFields = array(
+		'InvoiceID' => '', 			// Required.  ID of the invoice to mark paid.
+		'Note' => '', 		// Optional note associated with the payment.
+		'Date' => ''						// Date the invoice was paid.
+	);
+
+	$PayPalRequestData = array('MarkInvoiceAsRefundedFields' => $MarkInvoiceAsRefundedFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->MarkInvoiceAsRefunded($PayPalRequestData);
+	echo '
';
+	echo "

Deprecated Notice: The classic MarkInvoiceAsRefunded method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +// Write the contents of the response array to the screen for demo purposes. +print_r($PayPalResult); diff --git a/templates/sample-methods/RemindInvoice.php b/templates/sample-methods/RemindInvoice.php new file mode 100644 index 00000000..5945446e --- /dev/null +++ b/templates/sample-methods/RemindInvoice.php @@ -0,0 +1,50 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +// Prepare request arrays +$RemindInvoiceFields = array( + 'InvoiceID' => '', // ID of the invoice. +); + +$PayPalRequestData = array('RemindInvoiceFields' => $RemindInvoiceFields); + +if( $api_mode === 'rest' ){ + $RemindInvoiceFields['subject'] = ''; + $RemindInvoiceFields['note'] = ''; + $PayPalResult = $PayPal->RemindInvoice($PayPalRequestData); + echo '
';
+    print_r($PayPalResult);
+} else {
+    $RemindInvoiceFields['Subject'] = '';
+    $RemindInvoiceFields['NoteForPayer'] = '';
+    $PayPalResult = $PayPal->Adaptive->RemindInvoice($PayPalRequestData);
+
+    echo '
';
+    echo "

Deprecated Notice: The classic RemindInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + print_r($PayPalResult); +} diff --git a/templates/sample-methods/SearchInvoices.php b/templates/sample-methods/SearchInvoices.php new file mode 100644 index 00000000..51501b97 --- /dev/null +++ b/templates/sample-methods/SearchInvoices.php @@ -0,0 +1,90 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +if( $api_mode === 'rest' ){ + $SearchInvoicesFields = array( + 'Page' => '', // Required. Page number of result set, starting with 1 + 'PageSize' => '' // Required. Number of result pages, between 1 and 100 + ); + + $Parameters = array( + 'Email' => '', // Email search string + 'MerchantEmail' => '', // Required. Email address of invoice creator. + 'InvoiceNumber' => '', // Invoice number search string + 'Status' => '', // Invoice status search + 'LowerAmount' => '', // Invoice amount search. It specifies the smallest amount to be returned. If you pass a value for this field, you must also pass a CurrencyCode value. + 'UpperAmount' => '', // Invoice amount search. It specifies the largest amount to be returned. If you pass a value for this field, you must also pass a CurrencyCode value. + 'CurrencyCode' => '', // Currency used for lower and upper amounts. + 'Memo' => '', // Invoice memo search string + ); + + $PayPalRequestData = array( + 'SearchInvoicesFields' => $SearchInvoicesFields, + 'Parameters' => $Parameters + ); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->SearchInvoices($PayPalRequestData); + echo '
';
+} else {
+	// Prepare request arrays
+	$SearchInvoicesFields = array(
+		'MerchantEmail' => '', 		// Required.  Email address of invoice creator.
+		'Page' => '', 								// Required.  Page number of result set, starting with 1
+		'PageSize' => ''							// Required.  Number of result pages, between 1 and 100
+	);
+
+	$Parameters = array(
+		'Email' => '', 								// Email search string
+		'RecipientName' => '', 						// Recipient search string
+		'BusinessName' => '', 						// Company search string
+		'InvoiceNumber' => '', 						// Invoice number search string
+		'Status' => '', 							// Invoice status search
+		'LowerAmount' => '', 						// Invoice amount search.  It specifies the smallest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+		'UpperAmount' => '', 						// Invoice amount search.  It specifies the largest amount to be returned.  If you pass a value for this field, you must also pass a CurrencyCode value.
+		'CurrencyCode' => '', 						// Currency used for lower and upper amounts.  
+		'Memo' => '', 								// Invoice memo search string
+		'Origin' => '' 								// Indicates whether the invoice was created by the website or by an API call.  Values are:  Web, API
+		//'InvoiceDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice date range filter
+		//'DueDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice due Date range filter
+		//'PaymentDate' => array('StartDate' => '', 'EndDate' => ''), 		// Invoice payment date range filter.
+		//'CreationDate' => array('StartDate' => '', 'EndDate' => '')		// Invoice creation date range filter.
+	);
+
+	$PayPalRequestData = array(
+		'SearchInvoicesFields' => $SearchInvoicesFields, 
+		'Parameters' => $Parameters
+	);
+
+	$PayPalResult = $PayPal->Adaptive->SearchInvoices($PayPalRequestData);
+	echo '
';
+    echo "

Deprecated Notice: The classic SearchInvoices method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); diff --git a/templates/sample-methods/SendInvoice.php b/templates/sample-methods/SendInvoice.php new file mode 100644 index 00000000..8294606d --- /dev/null +++ b/templates/sample-methods/SendInvoice.php @@ -0,0 +1,41 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$InvoiceID = ''; + +if( $api_mode === 'rest' ){ + $PayPalResult = $PayPal->SendInvoice($InvoiceID); + echo '
';
+} else {
+	$PayPalResult = $PayPal->Adaptive->SendInvoice($InvoiceID);
+	echo '
';
+    echo "

Deprecated Notice: The classic SendInvoice method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); \ No newline at end of file diff --git a/templates/sample-methods/SetExpressCheckout.php b/templates/sample-methods/SetExpressCheckout.php new file mode 100644 index 00000000..045419db --- /dev/null +++ b/templates/sample-methods/SetExpressCheckout.php @@ -0,0 +1,192 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'APIVersion' => '97.0', + 'APISubject' => '', + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +$SECFields = array( + 'token' => '', // A timestamped token, the value of which was returned by a previous SetExpressCheckout call. + 'maxamt' => '', // The expected maximum total amount the order will be, including S&H and sales tax. + 'returnurl' => '', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => '', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'callback' => '', // URL to which the callback request from PayPal is sent. Must start with https:// for production. + 'callbacktimeout' => '', // An override for you to request more or less time to be able to process the callback request and response. Acceptable range for override is 1-6 seconds. If you specify greater than 6 PayPal will use default value of 3 seconds. + 'callbackversion' => '', // The version of the Instant Update API you're using. The default is the current version. + 'reqconfirmshipping' => '', // The value 1 indicates that you require that the customer's shipping address is Confirmed with PayPal. This overrides anything in the account profile. Possible values are 1 or 0. + 'noshipping' => '', // The value 1 indicates that on the PayPal pages, no shipping address fields should be displayed. Maybe 1 or 0. + 'addroverride' => '', // The value 1 indicates that the PayPal pages should display the shipping address set by you in the SetExpressCheckout request, not the shipping address on file with PayPal. This does not allow the customer to edit the address here. Must be 1 or 0. + 'localecode' => '', // Locale of pages displayed by PayPal during checkout. Should be a 2 character country code. You can retrive the country code by passing the country name into the class' GetCountryCode() function. + 'pagestyle' => '', // Sets the Custom Payment Page Style for payment pages associated with this button/link. + 'hdrimg' => '', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. + 'hdrbordercolor' => '', // Sets the border color around the header of the payment page. The border is a 2-pixel permiter around the header space. Default is black. + 'hdrbackcolor' => '', // Sets the background color for the header of the payment page. Default is white. + 'payflowcolor' => '', // Sets the background color for the payment page. Default is white. + 'skipdetails' => '', // This is a custom field not included in the PayPal documentation. It's used to specify whether you want to skip the GetExpressCheckoutDetails part of checkout or not. See PayPal docs for more info. + 'email' => '', // Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal sign-in page. 127 char max. + 'solutiontype' => '', // Type of checkout flow. Must be Sole (express checkout for auctions) or Mark (normal express checkout) + 'landingpage' => '', // Type of PayPal page to display. Can be Billing or Login. If billing it shows a full credit card form. If Login it just shows the login screen. + 'channeltype' => '', // Type of channel. Must be Merchant (non-auction seller) or eBayItem (eBay auction) + 'giropaysuccessurl' => '', // The URL on the merchant site to redirect to after a successful giropay payment. Only use this field if you are using giropay or bank transfer payment methods in Germany. + 'giropaycancelurl' => '', // The URL on the merchant site to redirect to after a canceled giropay payment. Only use this field if you are using giropay or bank transfer methods in Germany. + 'banktxnpendingurl' => '', // The URL on the merchant site to transfer to after a bank transfter payment. Use this field only if you are using giropay or bank transfer methods in Germany. + 'brandname' => '', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. + 'customerservicenumber' => '', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. + 'giftmessageenable' => '', // Enable gift message widget on the PayPal Review page. Allowable values are 0 and 1 + 'giftreceiptenable' => '', // Enable gift receipt widget on the PayPal Review page. Allowable values are 0 and 1 + 'giftwrapenable' => '', // Enable gift wrap widget on the PayPal Review page. Allowable values are 0 and 1. + 'giftwrapname' => '', // Label for the gift wrap option such as "Box with ribbon". 25 char max. + 'giftwrapamount' => '', // Amount charged for gift-wrap service. + 'buyeremailoptionenable' => '', // Enable buyer email opt-in on the PayPal Review page. Allowable values are 0 and 1 + 'surveyquestion' => '', // Text for the survey question on the PayPal Review page. If the survey question is present, at least 2 survey answer options need to be present. 50 char max. + 'surveyenable' => '', // Enable survey functionality. Allowable values are 0 and 1 + 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. 255 char max. + 'buyerusername' => '', // The user name of the user at the marketplaces site. + 'buyerregistrationdate' => '', // Date when the user registered with the marketplace. + 'allowpushfunding' => '' // Whether the merchant can accept push funding. 0 = Merchant can accept push funding : 1 = Merchant cannot accept push funding. +); + +// Basic array of survey choices. Nothing but the values should go in here. +$SurveyChoices = array('Yes', 'No'); + +$Payments = array(); +$Payment = array( + 'amt' => '', // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'currencycode' => '', // A three-character currency code. Default is USD. + 'itemamt' => '', // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. + 'shippingamt' => '', // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'insuranceoptionoffered' => '', // If true, the insurance drop-down on the PayPal review page displays the string 'Yes' and the insurance amount. If true, the total shipping insurance for this order must be a positive number. + 'handlingamt' => '', // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => '', // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'desc' => '', // Description of items on the order. 127 char max. + 'custom' => '', // Free-form field for your own use. 256 char max. + 'invnum' => '', // Your own invoice or tracking number. 127 char max. + 'notifyurl' => '', // URL for receiving Instant Payment Notifications + 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. + 'shiptostreet2' => '', // Second street address. 100 char max. + 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountry' => '', // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => '', // Phone number for shipping address. 20 char max. + 'notetext' => '', // Note to the merchant. 255 char max. + 'allowedpaymentmethod' => '', // The payment method type. Specify the value InstantPaymentOnly. + 'paymentaction' => '', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. + 'paymentrequestid' => '', // A unique identifier of the specific payment request, which is required for parallel payments. + 'sellerpaypalaccountid' => '' // A unique identifier for the merchant. For parallel payments, this field is required and must contain the Payer ID or the email address of the merchant. +); + +$PaymentOrderItems = array(); +$Item = array( + 'name' => '', // Item name. 127 char max. + 'desc' => '', // Item description. 127 char max. + 'amt' => '', // Cost of item. + 'number' => '', // Item number. 127 char max. + 'qty' => '', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => '', // URL for the item. + 'itemcategory' => '', // One of the following values: Digital, Physical + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); +array_push($PaymentOrderItems, $Item); + +$Item = array( + 'name' => '', // Item name. 127 char max. + 'desc' => '', // Item description. 127 char max. + 'amt' => '', // Cost of item. + 'number' => '', // Item number. 127 char max. + 'qty' => '', // Item qty on order. Any positive integer. + 'taxamt' => '', // Item sales tax + 'itemurl' => '', // URL for the item. + 'itemcategory' => '', // One of the following values: Digital, Physical + 'itemweightvalue' => '', // The weight value of the item. + 'itemweightunit' => '', // The weight unit of the item. + 'itemheightvalue' => '', // The height value of the item. + 'itemheightunit' => '', // The height unit of the item. + 'itemwidthvalue' => '', // The width value of the item. + 'itemwidthunit' => '', // The width unit of the item. + 'itemlengthvalue' => '', // The length value of the item. + 'itemlengthunit' => '', // The length unit of the item. + 'ebayitemnumber' => '', // Auction item number. + 'ebayitemauctiontxnid' => '', // Auction transaction ID number. + 'ebayitemorderid' => '', // Auction order ID number. + 'ebayitemcartid' => '' // The unique identifier provided by eBay for this order from the buyer. These parameters must be ordered sequentially beginning with 0 (for example L_EBAYITEMCARTID0, L_EBAYITEMCARTID1). Character length: 255 single-byte characters +); +array_push($PaymentOrderItems, $Item); + +$Payment['order_items'] = $PaymentOrderItems; +array_push($Payments, $Payment); + +$BuyerDetails = array( + 'buyerid' => '', // The unique identifier provided by eBay for this buyer. The value may or may not be the same as the username. In the case of eBay, it is different. Char max 255. + 'buyerusername' => '', // The username of the marketplace site. + 'buyerregistrationdate' => '' // The registration of the buyer with the marketplace. +); + +// For shipping options we create an array of all shipping choices similar to how order items works. +$ShippingOptions = array(); +$Option = array( + 'l_shippingoptionisdefault' => '', // Shipping option. Required if specifying the Callback URL. true or false. Must be only 1 default! + 'l_shippingoptionname' => '', // Shipping option name. Required if specifying the Callback URL. 50 character max. + 'l_shippingoptionlabel' => '', // Shipping option label. Required if specifying the Callback URL. 50 character max. + 'l_shippingoptionamount' => '' // Shipping option amount. Required if specifying the Callback URL. +); +array_push($ShippingOptions, $Option); + +$BillingAgreements = array(); +$Item = array( + 'l_billingtype' => '', // Required. Type of billing agreement. For recurring payments it must be RecurringPayments. You can specify up to ten billing agreements. For reference transactions, this field must be either: MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource + 'l_billingagreementdescription' => '', // Required for recurring payments. Description of goods or services associated with the billing agreement. + 'l_paymenttype' => '', // Specifies the type of PayPal payment you require for the billing agreement. Any or IntantOnly + 'l_billingagreementcustom' => '' // Custom annotation field for your own use. 256 char max. +); +array_push($BillingAgreements, $Item); + +$PayPalRequest = array( + 'SECFields' => $SECFields, + 'SurveyChoices' => $SurveyChoices, + 'BillingAgreements' => $BillingAgreements, + 'Payments' => $Payments +); + +$_SESSION['SetExpressCheckoutResult'] = $PayPal->SetExpressCheckout($PayPalRequest); + +$redirect_url = ''; +if( $api_mode === 'rest' && !$api_upgrade ) { + $redirect_url = $_SESSION['SetExpressCheckoutResult']['approval_url']; +} else { + $redirect_url = $_SESSION['SetExpressCheckoutResult']['REDIRECTURL']; +} + +echo 'Click here to continue.

'; +echo '
';
+print_r($_SESSION['SetExpressCheckoutResult']);

From d7e3a6d17f38031dd30a45d30bf8ba737ac8a01e Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Mon, 1 Dec 2025 12:29:44 +0530
Subject: [PATCH 056/146] Templates Samples Added

---
 .../sample-methods/GetInvoiceDetails.php      |  45 ++++++
 templates/sample-methods/MassPay.php          | 118 ++++++++++++++++
 templates/sample-methods/Refund.php           |  86 ++++++++++++
 .../sample-methods/RequestPermissions.php     |  83 +++++++++++
 .../sample-methods/UpdateAuthorization.php    |  46 +++++++
 .../UpdateRecurringPaymentsProfile.php        | 130 ++++++++++++++++++
 6 files changed, 508 insertions(+)
 create mode 100644 templates/sample-methods/GetInvoiceDetails.php
 create mode 100644 templates/sample-methods/MassPay.php
 create mode 100644 templates/sample-methods/Refund.php
 create mode 100644 templates/sample-methods/RequestPermissions.php
 create mode 100644 templates/sample-methods/UpdateAuthorization.php
 create mode 100644 templates/sample-methods/UpdateRecurringPaymentsProfile.php

diff --git a/templates/sample-methods/GetInvoiceDetails.php b/templates/sample-methods/GetInvoiceDetails.php
new file mode 100644
index 00000000..c34ea707
--- /dev/null
+++ b/templates/sample-methods/GetInvoiceDetails.php
@@ -0,0 +1,45 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+$InvoiceID = '';
+
+if( $api_mode === 'rest' ) {
+	$PayPalResult = $PayPal->GetInvoiceDetails($InvoiceID);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+} else {
+	$PayPalResult = $PayPal->Adaptive->GetInvoiceDetails($InvoiceID);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic GetInvoiceDetails method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); diff --git a/templates/sample-methods/MassPay.php b/templates/sample-methods/MassPay.php new file mode 100644 index 00000000..2ff8823b --- /dev/null +++ b/templates/sample-methods/MassPay.php @@ -0,0 +1,118 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +if( $api_mode === 'rest' ){ + + // Prepare request arrays + $SenderBatchHeaders = array( + 'sender_batch_id' => '', // A unique identifier of the batch payout. Must be unique for each payout. + "email_subject" => "", // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients. 255 char max. + "email_message" => "", // The message that PayPal sends to the recipients of the payout email. 255 char max. + ); + + // Typically, you'll loop through some sort of records to build your MPItems array. + // Here I simply include 3 items individually. + + $Item1 = array( + "recipient_type" => "", // The type of recipient. Must be EMAIL or PHONE. + "amount" => array( + "value" => "", // The amount to be paid to the recipient. + "currency" => "" // The currency code. + ), + "receiver" => "", // The recipient's email address. + "note" => "", // A note to the recipient. + "sender_item_id" => "" // A unique identifier for the item in the payout batch. + ); + + $Item2 = array( + "recipient_type" => "", // The type of recipient. Must be EMAIL or PHONE. + "amount" => array( + "value" => "", // The amount to be paid to the recipient. + "currency" => "" // The currency code. + ), + "receiver" => "", // The recipient's email address. + "note" => "", // A note to the recipient. + "sender_item_id" => "" // A unique identifier for the item in the payout batch. + ); + + $Item3 = array( + "recipient_type" => "", // The type of recipient. Must be EMAIL or PHONE. + "amount" => array( + "value" => "", // The amount to be paid to the recipient. + "currency" => "" // The currency code. + ), + "receiver" => "", // The recipient's email address. + "note" => "", // A note to the recipient. + "sender_item_id" => "" // A unique identifier for the item in the payout batch. + ); + + $Items = array($Item1, $Item2, $Item3); // etc + + $PayPalRequestData = array('sender_batch_header'=>$SenderBatchHeaders, 'items' => $Items); +} else { + + // Prepare request arrays + $MPFields = array( + 'emailsubject' => '', // The subject line of the email that PayPal sends when the transaction is completed. Same for all recipients. 255 char max. + 'currencycode' => '', // Three-letter currency code. + 'receivertype' => '' // Indicates how you identify the recipients of payments in this call to MassPay. Must be EmailAddress or UserID + ); + + // Typically, you'll loop through some sort of records to build your MPItems array. + // Here I simply include 3 items individually. + + $Item1 = array( + 'l_email' => '', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two. + 'l_receiverid' => '', // Required. ReceiverID of recipient. Must specify this or email address, but not both. + 'l_amt' => '', // Required. Payment amount. + 'l_uniqueid' => '', // Transaction-specific ID number for tracking in an accounting system. + 'l_note' => '' // Custom note for each recipient. + ); + + $Item2 = array( + 'l_email' => '', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two. + 'l_receiverid' => '', // Required. ReceiverID of recipient. Must specify this or email address, but not both. + 'l_amt' => '', // Required. Payment amount. + 'l_uniqueid' => '', // Transaction-specific ID number for tracking in an accounting system. + 'l_note' => '' // Custom note for each recipient. + ); + + $Item3 = array( + 'l_email' => '', // Required. Email address of recipient. You must specify either L_EMAIL or L_RECEIVERID but you must not mix the two. + 'l_receiverid' => '', // Required. ReceiverID of recipient. Must specify this or email address, but not both. + 'l_amt' => '', // Required. Payment amount. + 'l_uniqueid' => '', // Transaction-specific ID number for tracking in an accounting system. + 'l_note' => '' // Custom note for each recipient. + ); + + $MPItems = array($Item1, $Item2, $Item3); // etc + + $PayPalRequestData = array('MPFields'=>$MPFields, 'MPItems' => $MPItems); +} + +// Pass data into class for processing with PayPal and load the response array into $PayPalResult +$PayPalResult = $PayPal->MassPay($PayPalRequestData); + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
\ No newline at end of file
diff --git a/templates/sample-methods/Refund.php b/templates/sample-methods/Refund.php
new file mode 100644
index 00000000..f1f5045f
--- /dev/null
+++ b/templates/sample-methods/Refund.php
@@ -0,0 +1,86 @@
+ $sandbox,
+	'DeveloperAccountEmail' => $developer_account_email,
+	'ApplicationID' => $application_id,
+	'DeviceID' => $device_id,
+	'IPAddress' => $_SERVER['REMOTE_ADDR'],
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'APISubject' => $api_subject,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+	'isAdaptive' => true,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+
+if( $api_mode === 'rest' ) {
+
+	// Prepare request arrays
+	$RefundFields = array(
+		'value' => '',                            // Amount to refund.  Must not exceed the amount of the original payment.
+			'currency_code' => '',        		// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+	);
+
+	$PayPalRequestData = array(
+		'transaction_id' => '', 
+		'refund_fields' => array(
+					'amount' => $RefundFields,
+					"note_to_payer" => ""
+			),
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Refund($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+
+} else {
+
+	// Prepare request arrays
+	$RefundFields = array(
+		'CurrencyCode' => '', 				// Required.  Must specify code used for original payment.  You do not need to specify if you use a payKey to refund a completed transaction.
+		'PayKey' => '',  				// Required.  The key used to create the payment that you want to refund.
+		'TransactionID' => '',			 	// Required.  The PayPal transaction ID associated with the payment that you want to refund.
+		'TrackingID' => ''				// Required.  The tracking ID associated with the payment that you want to refund.
+	);
+
+	$Receivers = array();
+	$Receiver = array(
+		'Email' => '',					// A receiver's email address. 
+		'Amount' => '', 				// Amount to be debited to the receiver's account.
+		'Primary' => '', 				// Set to true to indicate a chained payment.  Only one receiver can be a primary receiver.  Omit this field, or set to false for simple and parallel payments.
+		'InvoiceID' => '', 				// The invoice number for the payment.  This field is only used in Pay API operation.
+		'PaymentType' => ''				// The transaction subtype for the payment.  Allowable values are: GOODS, SERVICE
+	);
+
+	array_push($Receivers, $Receiver);
+
+	$PayPalRequestData = array(
+		'RefundFields' => $RefundFields, 
+		'Receivers' => $Receivers
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->Refund($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic Refund method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; +} + +print_r($PayPalResult); \ No newline at end of file diff --git a/templates/sample-methods/RequestPermissions.php b/templates/sample-methods/RequestPermissions.php new file mode 100644 index 00000000..0f06ad35 --- /dev/null +++ b/templates/sample-methods/RequestPermissions.php @@ -0,0 +1,83 @@ + $sandbox, + 'DeveloperAccountEmail' => $developer_account_email, + 'ApplicationID' => $application_id, + 'DeviceID' => $device_id, + 'IPAddress' => $_SERVER['REMOTE_ADDR'], + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'APISubject' => $api_subject, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'isAdaptive' => true, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if( $api_mode === 'rest' ) { + + $PayPalResult = $PayPal->RequestPermissions(); + + // Write the contents of the response array to the screen for demo purposes. + echo '
';
+
+} else {
+
+	// Prepare request arrays
+	$Scope = array(
+		'EXPRESS_CHECKOUT', 
+		'DIRECT_PAYMENT', 
+	/*	'SETTLEMENT_CONSOLIDATION', 
+		'SETTLEMENT_REPORTING', 
+		'AUTH_CAPTURE', 
+		'MOBILE_CHECKOUT', 
+	*/	'BILLING_AGREEMENT', 
+		'REFERENCE_TRANSACTION', 
+	/*	'AIR_TRAVEL', 
+		'MASS_PAY', 
+	*/	'TRANSACTION_DETAILS',
+		'TRANSACTION_SEARCH',
+		'RECURRING_PAYMENTS',
+		'ACCOUNT_BALANCE',
+		'ENCRYPTED_WEBSITE_PAYMENTS',
+		'REFUND',
+		'NON_REFERENCED_CREDIT',
+		'BUTTON_MANAGER',
+		'MANAGE_PENDING_TRANSACTION_STATUS',
+		'RECURRING_PAYMENT_REPORT',
+		'EXTENDED_PRO_PROCESSING_REPORT',
+		'EXCEPTION_PROCESSING_REPORT',
+		'ACCOUNT_MANAGEMENT_PERMISSION',
+		'ACCESS_BASIC_PERSONAL_DATA',
+		'ACCESS_ADVANCED_PERSONAL_DATA'
+	);
+
+	$RequestPermissionsFields = array(
+		'Scope' => $Scope, 						// Required.   
+		'Callback' => ''						// Required.  Your callback function that specifies actions to take after the account holder grants or denies the request.
+	);
+
+	$PayPalRequestData = array('RequestPermissionsFields' => $RequestPermissionsFields);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->Adaptive->RequestPermissions($PayPalRequestData);
+
+	// Write the contents of the response array to the screen for demo purposes.
+	echo '
';
+	echo "

Deprecated Notice: The classic RequestPermissions method your plugin/theme is using has been deprecated. Please upgrade to the new REST-based implementation to ensure compatibility with future updates.

"; + +} + +print_r($PayPalResult); diff --git a/templates/sample-methods/UpdateAuthorization.php b/templates/sample-methods/UpdateAuthorization.php new file mode 100644 index 00000000..db207d94 --- /dev/null +++ b/templates/sample-methods/UpdateAuthorization.php @@ -0,0 +1,46 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret +); + +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +if ( $api_mode === 'rest' ) { + + $transactionID = ''; + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->UpdateAuthorization($transactionID); + +} else { + + // Prepare request arrays + $UAFields = array( + 'transactionid' => '', // Required. The value of the authorization's transaction identification number returned by a PayPal product. Char length: 17 single-byte chars. + 'ipaddress' => '' // IP address of the customer. + ); + + $PayPalRequestData = array('UAFields'=>$UAFields); + + // Pass data into class for processing with PayPal and load the response array into $PayPalResult + $PayPalResult = $PayPal->UpdateAuthorization($PayPalRequestData); +} + +// Write the contents of the response array to the screen for demo purposes. +echo '
';
+print_r($PayPalResult);
diff --git a/templates/sample-methods/UpdateRecurringPaymentsProfile.php b/templates/sample-methods/UpdateRecurringPaymentsProfile.php
new file mode 100644
index 00000000..f0da6344
--- /dev/null
+++ b/templates/sample-methods/UpdateRecurringPaymentsProfile.php
@@ -0,0 +1,130 @@
+ $sandbox,
+	'PayPalAPIMode' => $api_mode,
+	'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature, 
+	'PrintHeaders' => $print_headers,
+	'LogResults' => $log_results,
+	'LogPath' => $log_path,
+	'PayPalAPIUpgrade' => $api_upgrade,
+    'ClientID' => $rest_client_id,
+    'ClientSecret' => $rest_client_secret
+);
+
+$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
+
+
+if ( $api_mode === 'rest' ) { 
+
+	$ReplaceFields = array(
+		"op" => "",
+			"path" => "",
+			"value" => [
+					"currency_code" => "",
+					"value" => ""
+			]
+	);
+
+	$Patches = array($ReplaceFields);
+
+	// Prepare request arrays
+	$PayPalRequestData = array(
+			'subscription_id' => '',
+			'patches' => $Patches,
+	);
+
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->UpdateSubscriptionProfile($PayPalRequestData);
+
+} else {
+
+	// Prepare request arrays
+	$URPPFields = array(
+		'profileid' => '',		 		// Required.  Recurring payments ID.
+		'note' => '', 					// Note about the reason for the update to the profile.  Included in EC profile notification emails and in details pages.
+		'desc' => '', 					// Description of the recurring payment profile.
+		'subscribername' => '', 			// Full name of the person receiving the product or service paid for by the recurring payment profile.
+		'profilereference' => '', 			// The merchant's own unique reference or invoice number.
+		'additionalbillingcycles' => '', 		// The number of additional billing cycles to add to this profile.
+		'amt' => '',	 				// Billing amount for each cycle in the subscription, not including shipping and tax.  Express Checkout profiles can only be updated by 20% every 180 days.
+		'shippingamt' => '', 				// Shipping amount for each billing cycle during the payment period.
+		'taxamt' => '', 				// Tax amount for each billing cycle during the payment period.
+		'outstandingamt' => '', 			// The current past-due or outstanding amount.  You can only decrease this amount.  
+		'autobilloutamt' => '', 			// This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle.
+		'maxfailedpayments' => '', 			// The number of failed payments allowed before the profile is automatically suspended.  The specified value cannot be less than the current number of failed payments for the profile.
+		'profilestartdate' => ''			// The date when the billing for this profile begins.  UTC/GMT format.
+	);
+
+	$BillingAddress = array(
+		'street' => '', 		// Required.  First street address.
+		'street2' => '', 		// Second street address.
+		'city' => '', 			// Required.  Name of City.
+		'state' => '', 			// Required. Name of State or Province.
+		'countrycode' => '', 		// Required.  Country code.
+		'zip' => '', 			// Required.  Postal code of payer.
+		'phonenum' => '' 		// Phone Number of payer.  20 char max.
+	);
+
+	$ShippingAddress = array(
+		'shiptoname' => '', 		// Required if shipping is included.  Person's name associated with this address.  32 char max.
+		'shiptostreet' => '', 		// Required if shipping is included.  First street address.  100 char max.
+		'shiptostreet2' => '', 		// Second street address.  100 char max.
+		'shiptocity' => '', 		// Required if shipping is included.  Name of city.  40 char max.
+		'shiptostate' => '', 		// Required if shipping is included.  Name of state or province.  40 char max.
+		'shiptozip' => '', 		// Required if shipping is included.  Postal code of shipping address.  20 char max.
+		'shiptocountry' => '', 		// Required if shipping is included.  Country code of shipping address.  2 char max.
+		'shiptophonenum' => ''		// Phone number for shipping address.  20 char max.
+	);
+
+	$BillingPeriod = array(
+		'trialbillingperiod' => '', 
+		'trialbillingfrequency' => '', 
+		'trialtotalbillingcycles' => '', 
+		'trialamt' => '', 
+		'billingperiod' => '', 			// Required.  Unit for billing during this subscription period.  One of the following: Day, Week, SemiMonth, Month, Year
+		'billingfrequency' => '', 		// Required.  Number of billing periods that make up one billing cycle.  The combination of billing freq. and billing period must be less than or equal to one year. 
+		'totalbillingcycles' => '', 		// the number of billing cycles for the payment period (regular or trial).  For trial period it must be greater than 0.  For regular payments 0 means indefinite...until canceled.  
+		'amt' => '', 				// Required.  Billing amount for each billing cycle during the payment period.  This does not include shipping and tax. 
+		'currencycode' => '', 			// Required.  Three-letter currency code.
+	);
+
+	$CCDetails = array(
+		'creditcardtype' => '', 	// Required. Type of credit card.  Visa, MasterCard, Discover, Amex, Maestro, Solo.  If Maestro or Solo, the currency code must be GBP.  In addition, either start date or issue number must be specified.
+		'acct' => '', 			// Required.  Credit card number.  No spaces or punctuation.  
+		'expdate' => '', 		// Required.  Credit card expiration date.  Format is MMYYYY
+		'cvv2' => '', 			// Requirements determined by your PayPal account settings.  Security digits for credit card.
+		'startdate' => '', 		// Month and year that Maestro or Solo card was issued.  MMYYYY
+		'issuenumber' => ''		// Issue number of Maestro or Solo card.  Two numeric digits max.
+	);
+
+	$PayerInfo = array(
+		'email' => '', 			// Payer's email address.
+		'firstname' => '', 		// Required.  Payer's first name.
+		'lastname' => ''		// Required.  Payer's last name.
+	);
+				
+	$PayPalRequestData = array(
+		'URPPFields' => $URPPFields, 
+		'BillingAddress' => $BillingAddress, 
+		'ShippingAddress' => $ShippingAddress, 
+		'BillingPeriod' => $BillingPeriod, 
+		'CCDetails' => $CCDetails, 
+		'PayerInfo' => $PayerInfo
+	);
+
+	// Pass data into class for processing with PayPal and load the response array into $PayPalResult
+	$PayPalResult = $PayPal->UpdateRecurringPaymentsProfile($PayPalRequestData);
+
+}
+
+// Write the contents of the response array to the screen for demo purposes.
+echo '
';
+print_r($PayPalResult);

From dedb20d19400923538fc6acf9ae94dc0a629a868 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Wed, 10 Dec 2025 17:47:35 +0530
Subject: [PATCH 057/146] DemoKit Implementation for the ExpressCheckout Basic
 with Switching Logic

---
 .../DoExpressCheckoutPayment.php              |  36 ++--
 .../GetExpressCheckoutDetails.php             | 138 +++++++++++++--
 .../SetExpressCheckout.php                    |  41 +++--
 demo/index.php                                |   4 +-
 .../CapturePayment.php                        |  40 -----
 .../GetExpressCheckoutDetails.php             |  92 ----------
 .../ProcessPayments.php                       |  56 ------
 .../SetExpressCheckout.php                    |  85 ---------
 .../rest-checkout-line-items-v2/index.php     | 167 ------------------
 .../order-complete.php                        | 138 ---------------
 .../rest-checkout-line-items-v2/review.php    | 147 ---------------
 samples/classic/DoExpressCheckoutPayment.php  |   3 +-
 samples/rest/DoExpressCheckoutPayment.php     |   2 +-
 .../DoExpressCheckoutPayment.php              |   2 +-
 src/angelleye/PayPal/PayPalREST.php           |  27 +--
 15 files changed, 190 insertions(+), 788 deletions(-)
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/CapturePayment.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/ProcessPayments.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/index.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/order-complete.php
 delete mode 100644 demo/rest/rest-checkout-line-items-v2/review.php

diff --git a/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php b/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php
index bc813cdf..b36744a9 100644
--- a/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php
+++ b/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php
@@ -11,13 +11,16 @@
  */
 $PayPalConfig = array(
     'Sandbox' => $sandbox,
-    'PayPalAPIMode' => $api_mode,
+	'PayPalAPIMode' => $api_mode,
+    'PayPalAPIUpgrade' => $api_upgrade,
     'APIUsername' => $api_username,
-    'APIPassword' => $api_password,
-    'APISignature' => $api_signature,
-    'PrintHeaders' => $print_headers,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
 );
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
@@ -91,8 +94,7 @@
  * later into session variables, and then redirect to our final
  * thank you / receipt page.
  */
-if($PayPal->APICallSuccessful($PayPalResult['ACK']))
-{
+if( $api_mode === 'classic' && $PayPal->APICallSuccessful($PayPalResult['ACK']) ) {
     /**
      * Once again, since Express Checkout allows for multiple payments in a single transaction,
      * the DoExpressCheckoutPayment response is setup to provide data for each potential payment.
@@ -120,9 +122,21 @@
     }
 
     header('Location: order-complete.php');
-}
-else
-{
+} elseif( $api_mode === 'rest' && $PayPalResult['success'] ) {
+    $_SESSION['paypal_transaction_id'] = isset( $PayPalResult['capture_id'] ) ? $PayPalResult['capture_id'] : '';
+
+    $captures = ( $PayPalResult['purchase_units'][0]['payments']['captures'][0] ) ? $PayPalResult['purchase_units'][0]['payments']['captures'][0] : [];
+    $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00;
+    
+    header('Location: order-complete.php');
+} elseif( $api_mode === 'rest' && $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' ) {
+    $payments_info = isset( $PayPalResult['PAYMENTS'][0] ) ? $PayPalResult['PAYMENTS'][0] : [];
+
+    $_SESSION['paypal_transaction_id'] = isset($payments_info['TRANSACTIONID']) ? $payments_info['TRANSACTIONID'] : '';
+    $_SESSION['paypal_fee'] = isset($payments_info['FEEAMT']) ? $payments_info['FEEAMT'] : '0.00';
+    
+    header('Location: order-complete.php');
+} else {
     $_SESSION['paypal_errors'] = $PayPalResult['ERRORS'];
     header('Location: ../../error.php');
 }
\ No newline at end of file
diff --git a/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php b/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php
index 9d47371f..ba1f70f9 100644
--- a/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php
+++ b/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php
@@ -10,23 +10,70 @@
  * Then load the PayPal object into $PayPal
  */
 $PayPalConfig = array(
-    'Sandbox' => $sandbox,
-    'PayPalAPIMode' => $api_mode,
+	'Sandbox' => $sandbox,
+	'PayPalAPIMode' => $api_mode,
+    'PayPalAPIUpgrade' => $api_upgrade,
     'APIUsername' => $api_username,
-    'APIPassword' => $api_password,
-    'APISignature' => $api_signature,
-    'PrintHeaders' => $print_headers,
-    'LogResults' => $log_results,
-    'LogPath' => $log_path,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
 );
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
 
+$DECPFields = array(
+    'token' => $_SESSION['paypal_token'], 								// Required.  A timestamped token, the value of which was returned by a previous SetExpressCheckout call.
+    'payerid' => '', 							                        // Required.  Unique PayPal customer id of the payer.  Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL.
+);
+
+/**
+ * Just like with SetExpressCheckout, we need to gather our $Payment
+ * data to pass into our $Payments array.  This time we can include
+ * the shipping, handling, tax, and shipping address details that we
+ * now have.
+ */
+$Payments = array();
+$Payment = array(
+    'amt' => number_format($_SESSION['shopping_cart']['grand_total'],2), 	    // Required.  The total cost of the transaction to the customer.  If shipping cost and tax charges are known, include them in this value.  If not, this value should be the current sub-total of the order.
+    'itemamt' => number_format($_SESSION['shopping_cart']['subtotal'],2),       // Subtotal of items only.
+    'currencycode' => 'USD', 					                                // A three-character currency code.  Default is USD.
+    'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'],2), 	// Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
+    'handlingamt' => number_format($_SESSION['shopping_cart']['handling'],2), 	// Total handling costs for this order.  If you specify HANDLINGAMT you mut also specify a value for ITEMAMT.
+    'taxamt' => number_format($_SESSION['shopping_cart']['tax'],2), 			// Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
+    'shiptoname' => $_SESSION['shipping_name'], 					            // Required if shipping is included.  Person's name associated with this address.  32 char max.
+    'shiptostreet' => $_SESSION['shipping_street'], 					        // Required if shipping is included.  First street address.  100 char max.
+    'shiptocity' => $_SESSION['shipping_city'], 					            // Required if shipping is included.  Name of city.  40 char max.
+    'shiptostate' => $_SESSION['shipping_state'], 					            // Required if shipping is included.  Name of state or province.  40 char max.
+    'shiptozip' => $_SESSION['shipping_zip'], 						            // Required if shipping is included.  Postal code of shipping address.  20 char max.
+    'shiptocountrycode' => $_SESSION['shipping_country_code'], 				    // Required if shipping is included.  Country code of shipping address.  2 char max.
+    'shiptophonenum' => $_SESSION['phone_number'],  				            // Phone number for shipping address.  20 char max.
+    'paymentaction' => 'Sale', 					                                // How you want to obtain the payment.  When implementing parallel payments, this field is required and must be set to Order.
+);
+
 /**
- * Now we pass the PayPal token that we saved to a session variable
- * in the SetExpressCheckout.php file into the GetExpressCheckoutDetails
- * request.
+ * Here we push our single $Payment into our $Payments array.
  */
-$PayPalResult = $PayPal->GetExpressCheckoutDetails($_SESSION['paypal_token']);
+array_push($Payments, $Payment);
+
+/**
+ * Now we gather all of the arrays above into a single array.
+ */
+$PayPalRequestData = array(
+    'DECPFields' => $DECPFields, 
+    'Payments' => $Payments, 
+);
+
+/*
+ * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal
+ */
+if ( $api_mode === 'rest' ) {
+    $PayPalResult = $PayPal->GetExpressCheckoutDetails($PayPalRequestData);
+} else {
+    $PayPalResult = $PayPal->GetExpressCheckoutDetails($_SESSION['paypal_token']);
+}
 
 /**
  * Now we'll check for any errors returned by PayPal, and if we get an error,
@@ -36,8 +83,7 @@
  * If the call is successful, we'll save some data we might want to use
  * later into session variables.
  */
-if($PayPal->APICallSuccessful($PayPalResult['ACK']))
-{
+if( $api_mode === 'classic' && $PayPal->APICallSuccessful($PayPalResult['ACK']) ) {
     /**
      * Here we'll pull out data from the PayPal response.
      * Refer to the PayPal API Reference for all of the variables available
@@ -99,9 +145,69 @@
      * that has been added to the order.
      */
     header('Location: review.php');
-}
-else
-{
+} elseif( $api_mode === 'rest' && ($PayPalResult['success'] || ( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' )) ) {
+    /**
+     * Here we'll pull out data from the PayPal response.
+     */
+    $_SESSION['paypal_payer_id'] = ( ! $api_upgrade ) 
+                                    ? ( isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : '' )
+                                    : ( isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : '' );
+    $_SESSION['phone_number']   = ( ! $api_upgrade ) 
+                                    ? ( isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : '' )
+                                    : ( isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : '' );
+    $_SESSION['email']          = ( ! $api_upgrade ) 
+                                    ? ( isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : '' )
+                                    : ( isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : '' );
+    $_SESSION['first_name']     = ( ! $api_upgrade ) 
+                                    ? ( isset($PayPalResult['order']['payer']['name']['given_name']) ? $PayPalResult['order']['payer']['name']['given_name'] : '' )
+                                    : ( isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : '' );
+    $_SESSION['last_name']      = ( ! $api_upgrade ) 
+                                    ? ( isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : '' )
+                                    : ( isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : '' );
+    $_SESSION['billing_country_code'] = ( ! $api_upgrade ) 
+                                    ? ( isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : '' )
+                                    : ( isset($PayPalResult['COUNTRYCODE']) ? $PayPalResult['COUNTRYCODE'] : '' );
+
+    $purchaseUnit = $PayPalResult['order']['purchase_units'][0];
+    $shipping = ( ! $api_upgrade ) 
+                ? ( isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : [] )
+                : ( isset( $PayPalResult['SHIPPINGDATA'] ) ? $PayPalResult['SHIPPINGDATA'] : [] );    
+    $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : '';
+    $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : '';
+    $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : '';
+    $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : '';
+    $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : '';
+    $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : '';
+    $_SESSION['shipping_country_name'] = 'United States';
+
+    /**
+     * At this point, we now have the buyer's shipping address available in our app.
+     * We could now run the data through a shipping calculator to retrieve rate
+     * information for this particular order.
+     *
+     * This would also be the time to calculate any sales tax you may need to
+     * add to the order, as well as handling fees.
+     *
+     * We're going to set static values for these things in our static
+     * shopping cart, and then re-calculate our grand total.
+     */
+    $_SESSION['shopping_cart']['shipping'] = 10.00;
+    $_SESSION['shopping_cart']['handling'] = 2.50;
+    $_SESSION['shopping_cart']['tax'] = 1.50;
+
+    $_SESSION['shopping_cart']['grand_total'] = number_format(
+        $_SESSION['shopping_cart']['subtotal']
+        + $_SESSION['shopping_cart']['shipping']
+        + $_SESSION['shopping_cart']['handling']
+        + $_SESSION['shopping_cart']['tax'],2);
+
+    /**
+     * Now we will redirect the user to a final review
+     * page so they can see the shipping/handling/tax
+     * that has been added to the order.
+     */
+    header('Location: review.php');
+} else {
     $_SESSION['paypal_errors'] = $PayPalResult['ERRORS'];
     header('Location: ../../error.php');
 }
\ No newline at end of file
diff --git a/demo/classic/express-checkout-basic/SetExpressCheckout.php b/demo/classic/express-checkout-basic/SetExpressCheckout.php
index 222d21bc..05a9949e 100644
--- a/demo/classic/express-checkout-basic/SetExpressCheckout.php
+++ b/demo/classic/express-checkout-basic/SetExpressCheckout.php
@@ -12,11 +12,14 @@
 $PayPalConfig = array(
 	'Sandbox' => $sandbox,
 	'PayPalAPIMode' => $api_mode,
-	'APIUsername' => $api_username,
+        'PayPalAPIUpgrade' => $api_upgrade,
+        'APIUsername' => $api_username,
 	'APIPassword' => $api_password,
-	'APISignature' => $api_signature, 
+	'APISignature' => $api_signature,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
 	'PrintHeaders' => $print_headers, 
-	'LogResults' => $log_results,
+	'LogResults' => $log_results, 
 	'LogPath' => $log_path,
 );
 $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig);
@@ -76,22 +79,24 @@
  */
 $PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData);
 
-/**
- * Now we'll check for any errors returned by PayPal, and if we get an error,
- * we'll save the error details to a session and redirect the user to an 
- * error page to display it accordingly.
- *
- * If all goes well, we save our token in a session variable so that it's
- * readily available for us later, and then redirect the user to PayPal
- * using the REDIRECTURL returned by the SetExpressCheckout() function.
- */
-if($PayPal->APICallSuccessful($PayPalResult['ACK']))
-{
-    $_SESSION['paypal_token'] = isset($PayPalResult['TOKEN']) ? $PayPalResult['TOKEN'] : '';
-    header('Location: ' . $PayPalResult['REDIRECTURL']);
+$redirect_url = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+    $redirect_url = $PayPalResult['approval_url'];
+} else {
+    $redirect_url = $PayPalResult['REDIRECTURL'];
 }
-else
-{
+
+$orderId = '';
+if( $api_mode === 'rest' && !$api_upgrade ) {
+    $orderId = $PayPalResult['order_id'];
+} else {
+    $orderId = $PayPalResult['TOKEN'];
+}
+
+if($redirect_url) {
+    $_SESSION['paypal_token'] = $orderId;
+    header('Location: ' . $redirect_url);
+} else {
     $_SESSION['paypal_errors'] = $PayPalResult['ERRORS'];
     header('Location: ../../error.php');
 }
\ No newline at end of file
diff --git a/demo/index.php b/demo/index.php
index f531fcb2..0b8d59a9 100755
--- a/demo/index.php
+++ b/demo/index.php
@@ -83,12 +83,12 @@ interface so that you can see how everything flows together.

Learn how to integrate PayPal Checkout w/ Line Items using PayPal's REST API v2. It allows you to create and capture an order using the Orders API.

- Launch Demo + Launch Demo $sandbox, - 'PayPalAPIMode' => $api_mode, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$authorizationId = isset($_SESSION['authorization_id']) ? $_SESSION['authorization_id'] : ''; - -$PayPalResult = $PayPal->captureAutorizedOrder($authorizationId); - -if ($PayPalResult['success']) { - $_SESSION['paypal_transaction_id'] = isset($PayPalResult['capture_id']) ? $PayPalResult['capture_id'] : ''; - - // Get payment info - $getOrderDetails = $PayPal->getCapturedOrderDetails($PayPalResult['capture_id']); - - $_SESSION['paypal_fee'] = isset($getOrderDetails['full_response']['seller_receivable_breakdown']['paypal_fee']['value']) ? $getOrderDetails['full_response']['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; - - header('Location: order-complete.php'); - exit; -} else { - $_SESSION['paypal_errors'] = $PayPalResult['error']; - header('Location: ../../error.php'); -} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php b/demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php deleted file mode 100644 index f46968a7..00000000 --- a/demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php +++ /dev/null @@ -1,92 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$orderId = isset($_GET['token']) ? $_GET['token'] : ''; - -$PayPalResult = $PayPal->getOrder($orderId); - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If the call is successful, we'll save some data we might want to use - * later into session variables. - */ -if($PayPalResult['success']) { - $_SESSION['order_id'] = $orderId; - - // Get order details - $order = $PayPalResult['order']; - - // Basic Payer Info - $_SESSION['paypal_payer_id'] = isset($order['payer']['payer_id']) ? $order['payer']['payer_id'] : ''; - $_SESSION['phone_number'] = isset($order['payer']['phone']['phone_number']['national_number']) ? $order['payer']['phone']['phone_number']['national_number'] : ''; - $_SESSION['email'] = isset($order['payer']['email_address']) ? $order['payer']['email_address'] : ''; - $_SESSION['first_name'] = isset($order['payer']['name']['given_name']) ? $order['payer']['name']['given_name'] : ''; - $_SESSION['last_name'] = isset($order['payer']['name']['surname']) ? $order['payer']['name']['surname'] : ''; - $_SESSION['billing_country_code'] = isset($order['payer']['address']['country_code']) ? $order['payer']['address']['country_code'] : ''; - - // Shipping Address - $purchaseUnit = $order['purchase_units'][0]; - $shipping = isset($purchaseUnit['shipping']) ? $purchaseUnit['shipping'] : []; - - $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; - $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; - $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; - $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; - $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; - $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; - $_SESSION['shipping_country_name'] = 'United States'; // For demo purposes, we are assuming US. In real app, map country code to country name. - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - */ - $_SESSION['shopping_cart']['shipping'] = 10.00; - $_SESSION['shopping_cart']['handling'] = 2.50; - $_SESSION['shopping_cart']['tax'] = 1.50; - - $_SESSION['shopping_cart']['grand_total'] = number_format( - $_SESSION['shopping_cart']['subtotal'] - + $_SESSION['shopping_cart']['shipping'] - + $_SESSION['shopping_cart']['handling'] - + $_SESSION['shopping_cart']['tax'],2); - - /** - * Now we will redirect the user to a final review - * page so they can see the shipping/handling/tax - * that has been added to the order. - */ - header('Location: review.php'); - exit; -} else { - $_SESSION['paypal_errors'] = $PayPalResult['error']; - header('Location: ../../error.php'); -} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/ProcessPayments.php b/demo/rest/rest-checkout-line-items-v2/ProcessPayments.php deleted file mode 100644 index 2d2727e0..00000000 --- a/demo/rest/rest-checkout-line-items-v2/ProcessPayments.php +++ /dev/null @@ -1,56 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$paymentIntent = isset($_SESSION['payment_intent']) ? $_SESSION['payment_intent'] : 'CAPTURE'; - -$orderId = isset($_GET['token']) ? $_GET['token'] : ''; - -if ($paymentIntent === 'CAPTURE') { - // Capture order - $PayPalResult = $PayPal->captureOrder($orderId); - - if ($PayPalResult['success']) { - $_SESSION['paypal_transaction_id'] = $PayPalResult['capture_id'] ?? ''; - - $captures = $PayPalResult['purchase_units'][0]['payments']['captures'][0] ?? []; - $_SESSION['paypal_fee'] = $captures['seller_receivable_breakdown']['paypal_fee']['value'] ?? 0.00; - - header('Location: order-complete.php'); - exit; - } - -} else { - // Authorize order - $PayPalResult = $PayPal->authorizeOrder($orderId); - - if ($PayPalResult['success']) { - $_SESSION['authorization_id'] = $PayPalResult['authorization_id'] ?? ''; - - header('Location: CapturePayment.php'); - exit; - } -} - -// If there’s an error in either case -$_SESSION['paypal_errors'] = $PayPalResult['error'] ?? 'Unknown error'; -header('Location: ../../error.php'); -exit; diff --git a/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php b/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php deleted file mode 100644 index 9fc33484..00000000 --- a/demo/rest/rest-checkout-line-items-v2/SetExpressCheckout.php +++ /dev/null @@ -1,85 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$paymentIntent = isset($_SESSION['payment_intent']) ? $_SESSION['payment_intent'] : 'CAPTURE'; - -// Build PayPal order data from session -$orderData = [ - 'intent' => $paymentIntent, - 'purchase_units' => [ - [ - 'amount' => [ - 'currency_code' => 'USD', - 'value' => $_SESSION['shopping_cart']['grand_total'], - 'breakdown' => [ - 'item_total' => [ - 'currency_code' => 'USD', - 'value' => number_format($_SESSION['shopping_cart']['subtotal'], 2, '.', '') - ], - 'shipping' => [ - 'currency_code' => 'USD', - 'value' => number_format($_SESSION['shopping_cart']['shipping'], 2, '.', '') - ], - 'handling' => [ - 'currency_code' => 'USD', - 'value' => number_format($_SESSION['shopping_cart']['handling'], 2, '.', '') - ], - 'tax_total' => [ - 'currency_code' => 'USD', - 'value' => number_format($_SESSION['shopping_cart']['tax'], 2, '.', '') - ], - ], - ], - 'items' => array_map(function($item) { - return [ - 'name' => $item['name'], - 'sku' => $item['id'], - 'quantity' => (string)$item['qty'], - 'unit_amount' => [ - 'currency_code' => 'USD', - 'value' => number_format($item['price'], 2, '.', '') - ] - ]; - }, $_SESSION['shopping_cart']['items']), - ], - ], - 'application_context' => [ - 'brand_name' => 'Angell EYE', - 'landing_page' => 'BILLING', // or 'LOGIN' - 'user_action' => 'CONTINUE', - 'return_url' => $domain . 'demo/rest/rest-checkout-line-items-v2/GetExpressCheckoutDetails.php', - 'cancel_url' => $domain . 'demo/rest/rest-checkout-line-items-v2/', - ], -]; - -$PaymentResult = $PayPal->createOrder($orderData); - -if ($PaymentResult['success']) { - // Redirect to PayPal approval URL - header('Location: ' . $PaymentResult['approval_url']); - exit; -} else { - // Handle error - echo '

';
-    print_r($PaymentResult['error']);
-    echo '
'; -} \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/index.php b/demo/rest/rest-checkout-line-items-v2/index.php deleted file mode 100644 index dbcb712c..00000000 --- a/demo/rest/rest-checkout-line-items-v2/index.php +++ /dev/null @@ -1,167 +0,0 @@ - '123-ABC', - 'name' => 'Widget', - 'qty' => '2', - 'price' => '9.99', -); - -$_SESSION['items'][1] = array( - 'id' => 'XYZ-456', - 'name' => 'Gadget', - 'qty' => '1', - 'price' => '4.99', -); -$_SESSION['shopping_cart'] = array( - 'items' => $_SESSION['items'], - 'subtotal' => 24.97, - 'shipping' => 0, - 'handling' => 0, - 'tax' => 0, -); -$_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'],2); - -if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['checkout'])) { - $_SESSION['payment_intent'] = isset($_POST['payment_intent']) ? $_POST['payment_intent'] : 'CAPTURE'; - - // Redirect to checkout process (classic or REST) - header("Location: SetExpressCheckout.php"); - exit; -} - -?> - - - - PayPal Checkout with Line Items | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Shopping Cart


-

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any - billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal - after the user logs in and is returned back to the site.

-

To complete the demo, click the Checkout with PayPal button and use the following credentials to login to PayPal.

- Email Address: paypal-buyer@angelleye.com
- Password: paypalphp -

- - - - - - - - - - - - - - - - - - - - - -
IDNamePriceQTYTotal
$ $
-
-
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
Payment Intent - -
- -
-
-
-
-
-
-
- - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/order-complete.php b/demo/rest/rest-checkout-line-items-v2/order-complete.php deleted file mode 100644 index 251c295d..00000000 --- a/demo/rest/rest-checkout-line-items-v2/order-complete.php +++ /dev/null @@ -1,138 +0,0 @@ - - - - - PayPal Checkout with Line Items | Order Complete | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Payment Complete!


-

- We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID - to the Billing Information, which was provided in the captureOrder response. -

- - - - - - - - - - - - - - - - - - - - - -
IDNamePriceQTYTotal
$ $
-
-
-

Billing Information

-

- ' : ''); - echo (!empty($_SESSION['email']) ? $_SESSION['email'] . '
' : ''); - echo (!empty($_SESSION['phone_number']) ? $_SESSION['phone_number'] . '
' : ''); - echo (!empty($_SESSION['paypal_transaction_id']) ? $_SESSION['paypal_transaction_id'] : ''); - ?> -

-
-
-

Shipping Information

-

- ' : ''); - echo (!empty($_SESSION['shipping_street']) ? $_SESSION['shipping_street'] . '
' : ''); - echo (!empty($_SESSION['shipping_city']) ? $_SESSION['shipping_city'] . ', ' : ''); - echo (!empty($_SESSION['shipping_state']) ? $_SESSION['shipping_state'] . ' ' : ''); - echo (!empty($_SESSION['shipping_zip']) ? $_SESSION['shipping_zip'] . '
' : ''); - echo (!empty($_SESSION['shipping_country_name']) ? $_SESSION['shipping_country_name'] : ''); - ?> -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
 
-
-
-
-
-
- - - \ No newline at end of file diff --git a/demo/rest/rest-checkout-line-items-v2/review.php b/demo/rest/rest-checkout-line-items-v2/review.php deleted file mode 100644 index c77bf7c4..00000000 --- a/demo/rest/rest-checkout-line-items-v2/review.php +++ /dev/null @@ -1,147 +0,0 @@ - - - - - PayPal Checkout with Line Items | Order Review | PHP Class Library | Angell EYE - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -

Order Review


-

Display the final review page to the buyer using the details retrieved from the Get Order response — including shipping, handling, tax, and buyer-provided billing/shipping information. -

- -

- The payment has not been processed at this point because we have not yet called the final captureOrder API. That is what will happen when we click the "Complete Order" button below. -

- -

- The payment has not been captured yet because we have only created the order. Click on "Authorize & Capture Order" button below to authorize and capture the payment in one step. -

- - - - - - - - - - - - - - - - - - - - - - -
IDNamePriceQTYTotal
$ $
-
-
-

Billing Information

-

- ' : ''); - echo (!empty($_SESSION['email']) ? $_SESSION['email'] . '
' : ''); - echo (!empty($_SESSION['phone_number']) ? $_SESSION['phone_number'] . '' : ''); - ?> -

-
-
-

Shipping Information

-

- ' : ''); - echo (!empty($_SESSION['shipping_street']) ? $_SESSION['shipping_street'] . '
' : ''); - echo (!empty($_SESSION['shipping_city']) ? $_SESSION['shipping_city'] . ', ' : ''); - echo (!empty($_SESSION['shipping_state']) ? $_SESSION['shipping_state'] . ' ' : ''); - echo (!empty($_SESSION['shipping_zip']) ? $_SESSION['shipping_zip'] . '
' : ''); - echo (!empty($_SESSION['shipping_country_name']) ? $_SESSION['shipping_country_name'] : ''); - ?> -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
- - - -
-
-
-
-
-
- - \ No newline at end of file diff --git a/samples/classic/DoExpressCheckoutPayment.php b/samples/classic/DoExpressCheckoutPayment.php index 61c1ef2b..0f76f445 100644 --- a/samples/classic/DoExpressCheckoutPayment.php +++ b/samples/classic/DoExpressCheckoutPayment.php @@ -131,5 +131,6 @@ $_SESSION['PayPalResult'] = $PayPal -> DoExpressCheckoutPayment($PayPalRequest); -echo '
';
+echo 'DoExpressCheckoutPayment
';
 print_r($_SESSION['PayPalResult']);
+echo '

'; \ No newline at end of file diff --git a/samples/rest/DoExpressCheckoutPayment.php b/samples/rest/DoExpressCheckoutPayment.php index 7b4a919c..ea4de30c 100644 --- a/samples/rest/DoExpressCheckoutPayment.php +++ b/samples/rest/DoExpressCheckoutPayment.php @@ -28,6 +28,6 @@ echo '

'; $PaymentResult = $PayPal->captureOrder($orderId); -echo 'DoExpressCheckout
';
+echo 'DoExpressCheckoutPayment
';
 print_r($PaymentResult);
 echo '

'; \ No newline at end of file diff --git a/samples/sample-methods/DoExpressCheckoutPayment.php b/samples/sample-methods/DoExpressCheckoutPayment.php index a0569f70..7b5ff3d8 100644 --- a/samples/sample-methods/DoExpressCheckoutPayment.php +++ b/samples/sample-methods/DoExpressCheckoutPayment.php @@ -159,5 +159,5 @@ ); $_SESSION['PayPalResult'] = $PayPal->DoExpressCheckoutPayment($PayPalRequest); -echo 'DoExpressCheckout
';
+echo 'DoExpressCheckoutPayment
';
 print_r($_SESSION['PayPalResult']);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index c1bc963e..1071a940 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -747,9 +747,6 @@ function SetExpressCheckout($DataArray) {
                 "cancel_url" => isset($SECFields["cancelurl"]) ? $SECFields["cancelurl"] : "",
                 "brand_name" => isset($SECFields["brandname"]) ? $SECFields["brandname"] : "",
                 "landing_page" => strtoupper(isset($SECFields["landingpage"]) ? $SECFields["landingpage"] : "LOGIN"),
-                "shipping_preference" => (isset($SECFields["noshipping"]) && $SECFields["noshipping"] === "1")
-                    ? "NO_SHIPPING"
-                    : "SET_PROVIDED_ADDRESS"
             )
         );
 
@@ -804,6 +801,11 @@ function GetExpressCheckoutDetails($DataArray) {
             $responseData['FIRSTNAME'] = isset($response['order']['payer']['name']['given_name']) ? $response['order']['payer']['name']['given_name'] : '';
             $responseData['LASTNAME'] = isset($response['order']['payer']['name']['surname']) ? $response['order']['payer']['name']['surname'] : '';
             $responseData['COUNTRYCODE'] = isset($response['order']['payer']['address']['country_code']) ? $response['order']['payer']['address']['country_code'] : '';
+            
+            // Additional PAYER ADDRESS DETAILS
+            $purchaseUnit = $response['order']['purchase_units'][0];
+            $shipping = isset($purchaseUnit['shipping']) ? $purchaseUnit['shipping'] : [];
+            $responseData['SHIPPINGDATA'] = isset($shipping) ? $shipping : [];
 
             $responseData['DESC']   = isset($DataArray['Payments'][0]['desc']) ? $DataArray['Payments'][0]['desc'] : '';
             $responseData['CURRENCYCODE'] = isset($DataArray['Payments'][0]['currencycode']) ? $DataArray['Payments'][0]['currencycode'] : '';
@@ -935,16 +937,6 @@ function DoExpressCheckoutPayment($DataArray) {
         if ($this->api_upgrade && isset($response['success'])) {
             $responseData = array();
 
-            $responseData['TOKEN']  = isset($response['capture_id']) ? $response['capture_id'] : '';
-            $responseData['BILLINGAGREEMENTACCEPTEDSTATUS']  = false;
-            $responseData['NOTE']   = isset($DataArray['Payments'][0]['notetext']) ? $DataArray['Payments'][0]['notetext'] : '';
-            $responseData['CHECKOUTSTATUS'] = '';
-            $responseData['TIMESTAMP'] = gmdate('Y-m-d\TH:i:s\Z');
-            $responseData['CORRELATIONID'] = '';
-            $responseData['ACK'] = 'Success';
-            $responseData['INSURANCEOPTIONSELECTED'] = 'false';
-            $responseData['SHIPPINGOPTIONISDEFAULT'] = 'false';
-
             $fullResponse  = isset($response['full_response']) ? $response['full_response'] : array();
             $payer = isset($fullResponse['payer']) ? $fullResponse['payer'] : array();
 
@@ -984,6 +976,15 @@ function DoExpressCheckoutPayment($DataArray) {
 
             // Build NVP output
             $responseData = array(
+                "TOKEN"                                 => isset($response['capture_id']) ? $response['capture_id'] : '',
+                "BILLINGAGREEMENTACCEPTEDSTATUS"        => false,
+                "NOTE"                                  => isset($DataArray['Payments'][0]['notetext']) ? $DataArray['Payments'][0]['notetext'] : '',
+                "CHECKOUTSTATUS"                        => '',
+                "TIMESTAMP"                             => gmdate('Y-m-d\TH:i:s\Z'),
+                "CORRELATIONID"                         => '',
+                "ACK"                                   => 'Success',
+                "INSURANCEOPTIONSELECTED"               => 'false',
+                "SHIPPINGOPTIONISDEFAULT"               => 'false',
                 "PAYMENTINFO_0_TRANSACTIONID"           => isset($capture['id']) ? $capture['id'] : '',
                 "PAYMENTINFO_0_TRANSACTIONTYPE"         => "cart",
                 "PAYMENTINFO_0_PAYMENTTYPE"             => "instant",

From fdb1269e0034229caa417569edefcc57dd9ec3dd Mon Sep 17 00:00:00 2001
From: Drew Angell 
Date: Fri, 19 Dec 2025 11:30:23 -0600
Subject: [PATCH 058/146] Updates BN code, PPL-174

---
 src/angelleye/PayPal/PayPalClassic.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
index c3f9df2a..e99f1cc4 100644
--- a/src/angelleye/PayPal/PayPalClassic.php
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -92,7 +92,7 @@ function __construct($DataArray)
         $this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0';
         $this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature';
         $this->payPalAPIMode = isset($DataArray['payPalAPIMode']) ? $DataArray['payPalAPIMode'] : 'classic';
-        $this->APIButtonSource = 'AngellEYELLC_Ecom_PHPCatalog';
+        $this->APIButtonSource = 'AngellEYELLC_SI';
         $this->PathToCertKeyPEM = '/path/to/cert/pem.txt';
         $this->SSL = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? true : false;
         $this->APISubject = isset($DataArray['APISubject']) ? $DataArray['APISubject'] : '';

From 69792fd2534c465d6a80df3b2ae13ea298be09a1 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Tue, 23 Dec 2025 12:16:10 +0530
Subject: [PATCH 059/146] Added BN Code for the both Classic and REST via Main
 PayPal Class

---
 src/angelleye/PayPal/PayPal.php        |  1 +
 src/angelleye/PayPal/PayPalClassic.php |  4 +++-
 src/angelleye/PayPal/PayPalREST.php    | 12 +++++++-----
 3 files changed, 11 insertions(+), 6 deletions(-)

diff --git a/src/angelleye/PayPal/PayPal.php b/src/angelleye/PayPal/PayPal.php
index a24bb77a..bff46b86 100755
--- a/src/angelleye/PayPal/PayPal.php
+++ b/src/angelleye/PayPal/PayPal.php
@@ -46,6 +46,7 @@ class PayPal
     protected string $payPalAPIMode; // 'classic' or 'rest'
     protected bool $Sandbox = true;
     protected ?string $LogPath = null;
+    protected string $ButtonSource = 'AngellEYELLC_SI';
 
     public function __construct(array $config = [])
     {
diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
index e99f1cc4..1492c3c3 100644
--- a/src/angelleye/PayPal/PayPalClassic.php
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -79,6 +79,8 @@ class PayPalClassic extends PayPal
      */
     function __construct($DataArray)
     {
+        parent::__construct($DataArray);
+     
         if (isset($DataArray['Sandbox'])) {
             $this->Sandbox = $DataArray['Sandbox'];
         } else {
@@ -92,7 +94,7 @@ function __construct($DataArray)
         $this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0';
         $this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature';
         $this->payPalAPIMode = isset($DataArray['payPalAPIMode']) ? $DataArray['payPalAPIMode'] : 'classic';
-        $this->APIButtonSource = 'AngellEYELLC_SI';
+        $this->APIButtonSource = isset($this->ButtonSource) ? $this->ButtonSource : 'AngellEYELLC_SI';
         $this->PathToCertKeyPEM = '/path/to/cert/pem.txt';
         $this->SSL = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? true : false;
         $this->APISubject = isset($DataArray['APISubject']) ? $DataArray['APISubject'] : '';
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index 1071a940..f0ca3d08 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -18,6 +18,8 @@ class PayPalREST extends PayPal
 
     public function __construct($config)
     {
+        parent::__construct($config);
+
         $this->Sandbox = isset($config['Sandbox']) ? true : false;
 
         // Override base URL for REST API endpoints
@@ -50,11 +52,11 @@ public function test()
      * Get standard headers for API requests
      */
     private function getHeaders($includeAuth = true, $contentType = 'application/json', $requestId = null, $isInvoiceRequest = false)
-    {
+    {;
         $headers = [
-        'Content-Type: ' . $contentType,
-        'Accept: application/json',
-        'Partner-Attribution-Id: AngellEYELLC_Ecom_PHPCatalog'
+            'Content-Type: ' . $contentType,
+            'Accept: application/json',
+            'PayPal-Partner-Attribution-Id: ' . (isset($this->ButtonSource) ? $this->ButtonSource : 'AngellEYELLC_SI')
         ];
 
         if ($includeAuth) {
@@ -84,7 +86,7 @@ private function getOAuthHeaders()
             'Authorization: Basic ' . $auth,
             'Content-Type: application/x-www-form-urlencoded',
             'Accept: application/json',
-            'Partner-Attribution-Id: AngellEYELLC_Ecom_PHPCatalog'
+            'PayPal-Partner-Attribution-Id: ' . (isset($this->ButtonSource) ? $this->ButtonSource : 'AngellEYELLC_SI')
         ];
     }
 

From 1d005a7f5ea2149d29a450b354be7796789dae51 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Tue, 23 Dec 2025 17:29:13 +0530
Subject: [PATCH 060/146] Logging added for the REST and Updated for Classic

---
 src/angelleye/PayPal/PayPalClassic.php |  10 +-
 src/angelleye/PayPal/PayPalREST.php    | 259 +++++++++++++++++++++----
 2 files changed, 235 insertions(+), 34 deletions(-)

diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php
index 1492c3c3..4d6aaa9b 100644
--- a/src/angelleye/PayPal/PayPalClassic.php
+++ b/src/angelleye/PayPal/PayPalClassic.php
@@ -980,10 +980,18 @@ function Logger($log_path, $filename, $string_data)
     {
 
         if ($this->LogResults) {
+            // Create classic folder path
+            $classic_path = rtrim($log_path, '/') . '/classic/';
+
+            // Create folder if it doesn't exist
+            if (!is_dir($classic_path)) {
+                mkdir($classic_path, 0755, true);
+            }
+
             $timestamp = strtotime('now');
             $timestamp = date('mdY_gi_s_A_', $timestamp);
             $string_data_array = $this->NVPToArray($string_data);
-            $file = $log_path . $timestamp . $filename . '.txt';
+            $file = $classic_path . $timestamp . $filename . '.txt';
             $fh = fopen($file, 'w');
             fwrite($fh, $string_data . chr(13) . chr(13) . print_r($string_data_array, true));
             fclose($fh);
diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php
index f0ca3d08..c566f172 100644
--- a/src/angelleye/PayPal/PayPalREST.php
+++ b/src/angelleye/PayPal/PayPalREST.php
@@ -15,6 +15,8 @@ class PayPalREST extends PayPal
     private $client_secret;
     private $api_upgrade;
     private $base_url;
+    private $LogResults;
+    protected ?string $LogPath = null;
 
     public function __construct($config)
     {
@@ -31,6 +33,8 @@ public function __construct($config)
         $this->client_id = isset($config['ClientID']) ? $config['ClientID'] : '';
         $this->client_secret = isset($config['ClientSecret']) ? $config['ClientSecret'] : '';
         $this->api_upgrade = isset($config['PayPalAPIUpgrade']) ? $config['PayPalAPIUpgrade'] : FALSE;
+        $this->LogResults = isset($config['LogResults']) ? $config['LogResults'] : false;
+        $this->LogPath = isset($config['LogPath']) ? $config['LogPath'] : '/logs/';
 
         // Parent class already handles: sandbox, print_headers, log_results, log_path, base URLs
     }
@@ -192,16 +196,25 @@ function GetBalance($DataArray)
                         }
                     }
 
-                    return array_merge(
+                    $result = array_merge(
                         $flatBalances,
                         [
-                            'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
-                            'ACK' => 'Success',
+                            'TIMESTAMP'      => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
+                            'ACK'            => 'Success',
                             'BALANCERESULTS' => $balances,
-                            'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                            'RAWRESPONSE'    => isset($response['raw_response']) ? $response['raw_response'] : [],
                         ]
                     );
+
+                    // call logger
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+                    
+                    // return response
+                    return $result;
                 }
+                
+                // call logger
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
 
                 // Normal REST-style response
                 return [
@@ -211,6 +224,9 @@ function GetBalance($DataArray)
                 ];
             }
 
+            // call logger
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => '',
@@ -247,6 +263,10 @@ function AddBankAccount($DataArray) {
         // Step 3: Make REST Call
         $response = $this->makeRequest('/v1/vault/bank-accounts', 'POST', $payload);
 
+        // Log Request and Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $payload);
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
         // Step 4: Handle Response
         if ($response['status_code'] >= 200 && $response['status_code'] < 300) {
             return array(
@@ -308,6 +328,10 @@ function AddPaymentCard($DataArray) {
             );
         }
 
+        // Log Request and Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $payload);
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $responseSimplified);
+
         return $responseSimplified;
     }
 
@@ -334,6 +358,9 @@ function BMButtonSearch($DataArray) {
             );
         }
 
+        // Log Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
         return $responseSimplified;
     }
 
@@ -358,6 +385,9 @@ function BMGetButtonDetails($HostedButtonID) {
             );
         }
 
+        // Log Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $responseSimplified);
+
         return $responseSimplified;
     }
 
@@ -478,6 +508,9 @@ public function authorizeOrder($orderId)
         try {
             $response = $this->makeRequest('/v2/checkout/orders/' . $orderId . '/authorize', 'POST');
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -544,6 +577,9 @@ public function captureAutorizedOrder($authorizationId)
         try {
             $response = $this->makeRequest('/v2/payments/authorizations/' . $authorizationId . '/capture', 'POST');
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -575,6 +611,9 @@ public function getCapturedOrderDetails($captureId)
         try {
             $response = $this->makeRequest('/v2/payments/captures/' . $captureId, 'GET');
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -610,6 +649,34 @@ private function getApprovalUrl($links)
         return null;
     }
 
+    /**
+     * Save log info to a location on the disk.
+     *
+     * @param $log_path
+     * @param $filename
+     * @param $data
+     * @return bool
+     */
+    function Logger($log_path, $filename, $data) {
+        if ($this->LogResults) {
+            // REST log folder
+            $rest_path = rtrim($log_path, '/') . '/rest/';
+
+            // Create folder if not exists
+            if (!is_dir($rest_path)) {
+                mkdir($rest_path, 0755, true);
+            }
+
+            $timestamp = date('mdY_gi_s_A_');
+            $file = $rest_path . $timestamp . $filename . '.txt';
+
+            $fh = fopen($file, 'w');
+            fwrite($fh, print_r($data, true));
+            fclose($fh);
+        }
+        return true;
+    }
+
     public function DoDirectPayment($paymentData) {
         $paymentsMappedData = [];
 
@@ -678,6 +745,10 @@ public function DoDirectPayment($paymentData) {
             );
         }
 
+        // Log Request and Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $paymentsMappedData);
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $responseSimplified);
+
         return $responseSimplified;
     }
 
@@ -771,6 +842,10 @@ function SetExpressCheckout($DataArray) {
             );
         }
 
+        // Log Request and Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $payload);
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
         return $response;
     }
 
@@ -923,6 +998,9 @@ function ($it) {
             $responseData['RAWRESPONSE'] = isset($response['raw_response']) ? $response['raw_response'] : array();
         }
 
+        // Log Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', ($this->api_upgrade ? $responseData : $response));
+
         return $this->api_upgrade ? $responseData : $response;
     }
 
@@ -1032,6 +1110,9 @@ function DoExpressCheckoutPayment($DataArray) {
             $responseData['RAWRESPONSE'] = isset($response['raw_response']) ? $response['raw_response'] : array();
         }
 
+        // Log Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', ($this->api_upgrade ? $responseData : $response));
+
         return $this->api_upgrade ? $responseData : $response;
     }
 
@@ -1105,6 +1186,10 @@ public function CreateSubscriptionProfile($DataArray) {
             );
         }
 
+        // Log Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $DataArray);
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $responseSimplified);
+
         return $responseSimplified;
     }
 
@@ -1169,14 +1254,22 @@ public function GetSubscriptionProfile($DataArray) {
                         }
                     }
 
-                    return [
-                        'success' => true,
+                    $result = [
+                        'success'         => true,
                         'subscription_id' => isset($response['body']['id']) ? $response['body']['id'] : '',
-                        'status' => $response['body']['status'] ?? $response['status_code'],
-                        'full_response' => $fullResponse
+                        'status'          => $response['body']['status'] ?? $response['status_code'],
+                        'full_response'   => $fullResponse
                     ];
+
+                    // call logger
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                    return $result;
                 }
 
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1184,6 +1277,9 @@ public function GetSubscriptionProfile($DataArray) {
                 ];
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => '',
@@ -1213,19 +1309,26 @@ public function ManageSubscriptionProfile($DataArray) {
             $response = $this->makeRequest('/v1/billing/subscriptions/' . $subscriptionId . '/' . $subscriptionAction, 'POST', $subscriptionReason);
 
             if ( $response['status_code'] >= 200 && $response['status_code'] < 300 ) {
-
                 if ($this->api_upgrade) {
-                    return [
-                        'success' => true,
-                        'status' => $response['body']['status'] ?? $response['status_code'],
-                        'ACK' => 'Success',
-                        'TIMESTAMP' => gmdate('c'),
-                        'PROFILEID' => isset($subscriptionId) ? $subscriptionId : '',
+                    $result = [
+                        'success'        => true,
+                        'status'         => $response['body']['status'] ?? $response['status_code'],
+                        'ACK'            => 'Success',
+                        'TIMESTAMP'      => gmdate('c'),
+                        'PROFILEID'      => isset($subscriptionId) ? $subscriptionId : '',
                         'L_LONGMESSAGE0' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
-                        'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
+                        'full_response'  => isset($response['body']) ? $response['body'] : ['message' => 'Actions like cancel or suspend may not return a body'],
                     ];
+
+                    // call logger
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                    return $result;
                 }
 
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1233,6 +1336,9 @@ public function ManageSubscriptionProfile($DataArray) {
                 ];
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => '',
@@ -1264,17 +1370,25 @@ public function UpdateSubscriptionProfile($DataArray) {
             if ( $response['status_code'] >= 200 && $response['status_code'] < 300 ) {
 
                 if($this->api_upgrade) {
-                    return [
-                        'success' => true,
-                        'status' => $response['body']['status'] ?? $response['status_code'],
-                        'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
-                        'ACK' => 'Success',
+                    $result = [
+                        'success'        => true,
+                        'status'         => $response['body']['status'] ?? $response['status_code'],
+                        'TIMESTAMP'      => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
+                        'ACK'            => 'Success',
                         'L_LONGMESSAGE0' => 'Patch Operations completed successfully which may not return a body',
-                        'full_response' => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
-                        'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                        'full_response'  => isset($response['body']) ? $response['body'] : ['message' => 'Patch Operations completed successfully which may not return a body'],
+                        'RAWRESPONSE'    => isset($response['raw_response']) ? $response['raw_response'] : [],
                     ];
+
+                    // call logger
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                    return $result;
                 }
 
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1282,6 +1396,9 @@ public function UpdateSubscriptionProfile($DataArray) {
                 ];
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => '',
@@ -1308,23 +1425,34 @@ public function UpdateAuthorization($transactionId)
         try {
             $response = $this->makeRequest('/v2/payments/authorizations/' . $transactionId . '/reauthorize', 'POST');
             if ( $response['status_code'] >= 200 && $response['status_code'] < 300 ) {
-
                 if( $this->api_upgrade ) {
-                    return [
-                        'success' => true,
-                        'TIMESTAMP' => '2025-11-26T16:51:14Z',
-                        'ACK' => 'Success',
+                    $result = [
+                        'success'        => true,
+                        'TIMESTAMP'      => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
+                        'ACK'            => 'Success',
                         'L_LONGMESSAGE0' => isset($response['body']['details']['message']) ? $response['body']['details']['message'] : '',
-                        'order' => $response['body'],
-                        'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
+                        'order'          => $response['body'],
+                        'RAWRESPONSE'    => isset($response['raw_response']) ? $response['raw_response'] : [],
                     ];
+
+                    // call logger
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                    return $result;
                 }
+                
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
                 return [
                     'success' => true,
                     'order' => $response['body']
                 ];
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => 'Failed to get order details',
@@ -1353,6 +1481,9 @@ public function Refund($DataArray) {
 
             $response = $this->makeRequest('/v2/payments/captures/' . $transactionId . '/refund', 'POST', $refundFields);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1389,7 +1520,7 @@ public function MassPay($DataArray) {
             if ($response['status_code'] === 201) {
 
                 if( $this->api_upgrade ) {
-                    return [
+                    $result = [
                         'ACK' => 'Success',
                         'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
                         'success' => true,
@@ -1398,7 +1529,16 @@ public function MassPay($DataArray) {
                         'full_response' => $response['body'],
                         'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
                     ];
+
+                    // Log Response
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                    return $result;
                 }
+
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1406,6 +1546,9 @@ public function MassPay($DataArray) {
                 ];
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => '',
@@ -1435,15 +1578,23 @@ public function GetPalDetails() {
             if (in_array($response['status_code'], [200, 201])) {
 
                 if ($this->api_upgrade) {
-                    return [
+                    $result = [
                         'PAL' => isset($response['body']['payer_id']) ? $response['body']['payer_id'] : '',
                         'TIMESTAMP' => isset($body['as_of_time']) ? $body['as_of_time'] : gmdate('c'),
                         'ACK' => 'Success',
                         'full_response' => $response['body'],
                         'RAWRESPONSE' => isset($response['raw_response']) ? $response['raw_response'] : [],
                     ];
+
+                    // Log Response
+                    $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                    return $result;
                 }
 
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
                 return [
                     'success' => true,
                     'status' => $response['body']['status'] ?? $response['status_code'],
@@ -1451,6 +1602,9 @@ public function GetPalDetails() {
                 ];
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'error' => '',
@@ -1580,6 +1734,9 @@ public function RequestPermissions() {
         try {
             $response = $this->makeRequest('/v1/identity/oauth2/userinfo?schema=openid');
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1613,6 +1770,9 @@ public function CreateInvoice($InvoiceData)
         try {
             $response = $this->makeRequest('/v2/invoicing/invoices', 'POST', $InvoiceData, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1648,6 +1808,9 @@ public function SendInvoice($InvoiceID)
         try {
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/send', 'POST', null, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1716,6 +1879,9 @@ public function CreateAndSendInvoice($InvoiceData)
             );
         }
 
+        // Log Response
+        $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $responseSimplified);
+
         return $responseSimplified;
     }
 
@@ -1730,6 +1896,9 @@ public function GetInvoiceDetails($InvoiceID)
         try {
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID, 'GET', null, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1774,6 +1943,10 @@ public function CancelInvoice($InvoiceData)
 
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/cancel', 'POST', $payload, null, true);
 
+            // Log Request and Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Request', $payload);
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1809,6 +1982,9 @@ public function DeleteInvoice($InvoiceID)
         try {
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID, 'DELETE', null, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1849,6 +2025,9 @@ public function MarkInvoiceAsPaid($InvoiceData)
 
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/payments', 'POST', $payload, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1886,6 +2065,9 @@ public function MarkInvoiceAsRefunded($InvoiceData)
 
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/refunds', 'POST', $payload, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -1922,6 +2104,9 @@ public function RemindInvoice($InvoiceData)
 
             $response = $this->makeRequest('/v2/invoicing/invoices/' . $InvoiceID . '/remind', 'POST', $payload, null, true);
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             if ($response['status_code'] === 201) {
                 return [
                     'success' => true,
@@ -2030,14 +2215,22 @@ public function SearchInvoices($InvoiceData)
                     return $statusMatch && $emailMatch && $invoiceEmailMatch && $invoiceNumberMatch && $currencyMatch && $amountMatch && $memoMatch;
                 });
 
-                return [
+                $result = [
                     'success' => true,
                     'status_code' => $response['status_code'],
                     'total_items' => count($filteredInvoices),
                     'invoices' => array_values($filteredInvoices),
                 ];
+
+                // Log Response
+                $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $result);
+
+                return $result;
             }
 
+            // Log Response
+            $this->Logger($this->LogPath, __FUNCTION__ . 'Response', $response);
+
             return [
                 'success' => false,
                 'status_code' => $response['status_code'],

From 23d379125192ca0909b538199cac453222d738b3 Mon Sep 17 00:00:00 2001
From: meet-creedally 
Date: Thu, 25 Dec 2025 12:23:55 +0530
Subject: [PATCH 061/146] Added Function for PayPal Button using JS SDKv6 and
 not for the Classic Users

---
 demo/assets/css/style.css                     | 137 ++++++++++++++++--
 demo/assets/images/cart.svg                   |   7 +
 demo/classic/express-checkout-basic/index.php |  90 +++++++-----
 .../express-checkout-basic/order-complete.php | 108 +++++++-------
 .../classic/express-checkout-basic/review.php | 102 +++++++------
 .../PayPal/PayPalCommonFunctions.php          |  53 +++++++
 src/angelleye/PayPal/PayPalREST.php           |  17 ++-
 src/angelleye/PayPal/api/token.php            |  20 +++
 8 files changed, 379 insertions(+), 155 deletions(-)
 create mode 100644 demo/assets/images/cart.svg
 create mode 100644 src/angelleye/PayPal/PayPalCommonFunctions.php
 create mode 100644 src/angelleye/PayPal/api/token.php

diff --git a/demo/assets/css/style.css b/demo/assets/css/style.css
index fadc1189..3ec3429c 100755
--- a/demo/assets/css/style.css
+++ b/demo/assets/css/style.css
@@ -1,29 +1,138 @@
 @charset "utf-8";
 /* CSS Document */
 
+#header {
+    display: flex;
+    align-items: center;
+    margin: 10px 0;
+}
+#header .column {
+    padding: 0;
+}
+#angelleye_logo img,
+#paypal_partner_logo img {
+    width: 240px;
+}
 #paypal_partner_logo {
-    width: 351px;
-    height: 49px;
-    float:right;
-    margin: 5% 0 3% 0;
+    float: right;
+}
+.warning-info {
+    display: flex;
+    align-items: center;
+    gap: 10px;
+    padding: 16px 24px;
+    background: #FCF9E7;
+    color: #3F3F3F;
+    font-size: 14px;
+    border-left: 4px solid #F0C100;
+    margin-top: 20px;
+}
+.warning-info .warning-icon {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    background: #F0C100;
+    color: #FFF;
+    padding: 2px;
+    border-radius: 50%;
+    width: 22px;
+    height: 22px;
+}
+.main-title {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    gap: 10px;
+    margin: 20px 0;
+}
+.main-title img {
+    width: 32px;
+    height: 32px;
+}
+.main-info {
+    font-size: 16px;
+    margin-bottom: 20px;
+}
+.demo-cred {
+    background: #EFF6FF;
+    padding: 24px;
+    border-left: 4px solid;
+    border-left-color: #3B82F6;
+}
+.demo-cred h2 {
+    font-size: 16px;
+    font-weight: 700;
+    color: #1E3A8A;
+    margin: 0 0 12px 0;
+}
+.demo-cred p {
+    color: #1E40AF;
+    margin-bottom: 4px;
+}
+.table-items {
+    margin: 20px 0;
+}
+.table-items thead {
+    background: #F4f4F4;
+}
+.table-items thead th {
+    text-transform: uppercase;
+    font-weight: 500;
+}
+.table-items thead th:not(:last-child) {
+    border-right: 2px solid #DDD;
+}
+.table-items tbody td:not(:last-child) {
+    border-right: 1px solid #DDD;
+}
+.table-summary tr td {
+    border-top: none !important;
+    padding: 4px !important;
+}
+.table-summary tr td:last-child {
+    text-align: end !important;
+}
+.table-summary tr td.total-border-top {
+    border-top: 2px solid #DDD !important;
+}
+.font-lightbold {
+    font-weight: 500;
+}
+.table-items th,
+.table-items td {
+    font-size: 14px;
 }
-
 th.center {
-	text-align:center;
+	text-align: center;
 }
-
-td.center{
-	text-align:center;	
+td.center {
+	text-align: center;
+}
+.table-summary tr td.button-center {
+    padding: 0 !important;
+}
+.button-center a {
+    background-color: #4F46E5;
+    border-color: #4F46E5;
+    margin: 20px 0 10px;
+}
+.button-center a:hover {
+    background-color: #4338CA;
+    border-color: #4338CA;
+}
+.table-summary .paypalbtn {
+    padding: 0 !important;
+}
+.paypalbtn a {
+    display: block;
+    margin: 20px 0;
 }
-
 #paypal_errors {
-	margin-top:25px;	
+	margin-top: 25px;
 }
-
 .general_message {
 	margin: 20px 0 20px 0;	
 }
-
 .bg-info {
-	padding:15px;	
+	padding: 15px;	
 }
\ No newline at end of file
diff --git a/demo/assets/images/cart.svg b/demo/assets/images/cart.svg
new file mode 100644
index 00000000..9a8bbcd6
--- /dev/null
+++ b/demo/assets/images/cart.svg
@@ -0,0 +1,7 @@
+
+

+
+

+

+
  
+

\ No newline at end of file
diff --git a/demo/classic/express-checkout-basic/index.php b/demo/classic/express-checkout-basic/index.php
index e3186647..d8c5a841 100644
--- a/demo/classic/express-checkout-basic/index.php
+++ b/demo/classic/express-checkout-basic/index.php
@@ -1,5 +1,25 @@
  $sandbox,
+	'PayPalAPIMode' => $api_mode,
+  'PayPalAPIUpgrade' => $api_upgrade,
+  'APIUsername' => $api_username,
+	'APIPassword' => $api_password,
+	'APISignature' => $api_signature,
+	'ClientID' => $rest_client_id,
+	'ClientSecret' => $rest_client_secret,
+	'PrintHeaders' => $print_headers, 
+	'LogResults' => $log_results, 
+	'LogPath' => $log_path,
+);
+$PayPalCommonFunctions = new angelleye\PayPal\PayPalCommonFunctions($PayPalConfig);
 
 /**
  * Here we are building a very simple, static shopping cart to use
@@ -58,6 +78,8 @@
 
 
 
+
+
 
 
 
@@ -72,68 +94,70 @@
           
         
       
-      

Shopping Cart

-

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any + +

+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

CartShopping Cart

+

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal after the user logs in and is returned back to the site.

-

To complete the demo, click the Checkout with PayPal button and use the following credentials to login to PayPal.

- Email Address: paypal-buyer@angelleye.com
- Password: paypalphp -

- +
+

Demo Credentials

+

Email: paypal-buyer@angelleye.com

+

Password: paypalphp

+
+
- - + + - + - - + + - - + + - +
IDNameIDName Price QTY Total
$ $ $
-
-
- +
+
+
- - + + - - + + - - + + - - + + - - + + - +
Subtotal $Subtotal$
Shipping$Shipping$
Handling$Handling$
Tax$Tax$
Grand Total$Grand Total$
renderPayPalButton(); ?>
diff --git a/demo/classic/express-checkout-basic/order-complete.php b/demo/classic/express-checkout-basic/order-complete.php index 5d057d4a..6dccd738 100644 --- a/demo/classic/express-checkout-basic/order-complete.php +++ b/demo/classic/express-checkout-basic/order-complete.php @@ -45,35 +45,37 @@
-

Payment Complete!

-

- We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID - to the Billing Information, which was provided in the DoExpressCheckoutPayment response. -

- + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

Payment Complete!

+

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID + to the Billing Information, which was provided in the DoExpressCheckoutPayment response.

+
- - + + - - - - - - - - - + + + + + + + + +
IDNameIDName Price QTY Total
$ $
$ $
@@ -81,49 +83,49 @@

Billing Information

' . - $_SESSION['email'] . '
'. - $_SESSION['phone_number'] . '
' . - $_SESSION['paypal_transaction_id']; - ?> + echo $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '
' . + $_SESSION['email'] . '
'. + $_SESSION['phone_number'] . '
' . + $_SESSION['paypal_transaction_id']; + ?>

Shipping Information

' . - $_SESSION['shipping_street'] . '
' . - $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . - $_SESSION['shipping_country_name']; - ?> + echo $_SESSION['shipping_name'] . '
' . + $_SESSION['shipping_street'] . '
' . + $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . + $_SESSION['shipping_country_name']; + ?>

- +
- - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + +
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
 Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
 
diff --git a/demo/classic/express-checkout-basic/review.php b/demo/classic/express-checkout-basic/review.php index 99e1866d..daef1170 100644 --- a/demo/classic/express-checkout-basic/review.php +++ b/demo/classic/express-checkout-basic/review.php @@ -45,38 +45,36 @@
-

Order Review

-

Here we display a final review to the buyer now that we've calculated shipping, handling, and tax. The - billing and shipping information provided here is what we obtained in the GetExpressCheckoutDetails response. -

-

- The payment has not been processed at this point because we have not yet called the final DoExpressCheckoutPayment API. That is what will - happen when we click the "Complete Order" button below. -

- + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

Order Review

+

Here we display a final review to the buyer now that we've calculated shipping, handling, and tax. The + billing and shipping information provided here is what we obtained in the GetExpressCheckoutDetails response.

+

The payment has not been processed at this point because we have not yet called the final DoExpressCheckoutPayment API. That is what will + happen when we click the "Complete Order" button below.

+
- - + + - + - - + + - - + + - +
IDNameIDName Price QTY Total
$ $ $
@@ -84,48 +82,48 @@

Billing Information

' . - $_SESSION['email'] . '
'. - $_SESSION['phone_number'] . '
'; - ?> + echo $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '
' . + $_SESSION['email'] . '
'. + $_SESSION['phone_number'] . '
'; + ?>

Shipping Information

' . - $_SESSION['shipping_street'] . '
' . - $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . - $_SESSION['shipping_country_name']; - ?> + echo $_SESSION['shipping_name'] . '
' . + $_SESSION['shipping_street'] . '
' . + $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . + $_SESSION['shipping_country_name']; + ?>

- +
- - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + +
Subtotal $
Shipping$
Handling$
Tax$
Grand Total$
Complete OrderSubtotal$
Shipping$
Handling$
Tax$
Grand Total$
Complete Order
diff --git a/src/angelleye/PayPal/PayPalCommonFunctions.php b/src/angelleye/PayPal/PayPalCommonFunctions.php new file mode 100644 index 00000000..2ec3d2f4 --- /dev/null +++ b/src/angelleye/PayPal/PayPalCommonFunctions.php @@ -0,0 +1,53 @@ +config = $config; + $this->mode = isset($config['Sandbox']) ? $config['Sandbox'] : 'live'; + } + + /** + * Render the PayPal payment button + */ + public function renderPayPalButton() + { + if ($this->config['PayPalAPIMode'] !== 'rest') { + echo ''; + return; + } + + $sdk_url = ( $this->mode === 'sandbox' ) ? "https://www.sandbox.paypal.com/web-sdk/v6/core" : "https://www.paypal.com/web-sdk/v6/core"; + ?> + + + + + + + + accessToken && $this->tokenExpiry > time()) { @@ -106,12 +106,16 @@ private function getAccessToken() } $headers = $this->getOAuthHeaders(); - $postData = 'grant_type=client_credentials'; + $postData = ['grant_type' => 'client_credentials']; + + if ($load_sdk_btn) { + $postData['response_type'] = 'client_token'; + } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->base_url . '/v1/oauth2/token'); curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); @@ -132,6 +136,13 @@ private function getAccessToken() throw new \Exception('Failed to get OAuth token: ' . $response); } + /** + * Public method for external access + **/ + public function fetchAccessToken( $load_sdk_btn = false ){ + return $this->getAccessToken( $load_sdk_btn ); + } + /** * Make authenticated REST API request */ diff --git a/src/angelleye/PayPal/api/token.php b/src/angelleye/PayPal/api/token.php new file mode 100644 index 00000000..0079b5f6 --- /dev/null +++ b/src/angelleye/PayPal/api/token.php @@ -0,0 +1,20 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); + +$paypalRest = new angelleye\PayPal\PayPalREST($PayPalConfig); +$token = $paypalRest->fetchAccessToken(true); + +echo json_encode(['token' => $token]); \ No newline at end of file From 17f0a4b8356995cddbb13f874f69f8d0a2a5171e Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 29 Dec 2025 10:35:12 +0530 Subject: [PATCH 062/146] Updated ButtonSource in Classic same as REST --- samples/config/config-sample.php | 10 ++++++++++ src/angelleye/PayPal/PayPalClassic.php | 8 +++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/samples/config/config-sample.php b/samples/config/config-sample.php index 4f9dc980..5ac673e1 100755 --- a/samples/config/config-sample.php +++ b/samples/config/config-sample.php @@ -41,6 +41,16 @@ */ $api_mode = 'classic'; // Options: 'classic' or 'rest' +/** + * PayPal API Upgrade Option + * ------------------------- + * If TRUE, the library will auto-upgrade Classic API calls to REST mode, + * mapping Classic parameters to REST and returning normalized responses. + * If FALSE, Classic and REST modes work separately, and REST responses + * are returned as-is. + */ +$api_upgrade = FALSE; // Options: TRUE or FALSE + /** * PayPal API Version * ------------------ diff --git a/src/angelleye/PayPal/PayPalClassic.php b/src/angelleye/PayPal/PayPalClassic.php index 4d6aaa9b..c84d0c64 100644 --- a/src/angelleye/PayPal/PayPalClassic.php +++ b/src/angelleye/PayPal/PayPalClassic.php @@ -46,7 +46,6 @@ class PayPalClassic extends PayPal var $APISignature = ''; var $APISubject = ''; var $APIVersion = ''; - var $APIButtonSource = ''; var $APIMode = ''; var $EndPointURL = ''; var $PathToCertKeyPEM = ''; @@ -94,7 +93,6 @@ function __construct($DataArray) $this->APIVersion = isset($DataArray['APIVersion']) ? $DataArray['APIVersion'] : '204.0'; $this->APIMode = isset($DataArray['APIMode']) ? $DataArray['APIMode'] : 'Signature'; $this->payPalAPIMode = isset($DataArray['payPalAPIMode']) ? $DataArray['payPalAPIMode'] : 'classic'; - $this->APIButtonSource = isset($this->ButtonSource) ? $this->ButtonSource : 'AngellEYELLC_SI'; $this->PathToCertKeyPEM = '/path/to/cert/pem.txt'; $this->SSL = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? true : false; $this->APISubject = isset($DataArray['APISubject']) ? $DataArray['APISubject'] : ''; @@ -122,7 +120,7 @@ function __construct($DataArray) } // Create the NVP credentials string which is required in all calls. - $this->NVPCredentials = 'USER=' . $this->APIUsername . '&PWD=' . $this->APIPassword . '&VERSION=' . $this->APIVersion . '&BUTTONSOURCE=' . $this->APIButtonSource; + $this->NVPCredentials = 'USER=' . $this->APIUsername . '&PWD=' . $this->APIPassword . '&VERSION=' . $this->APIVersion . '&BUTTONSOURCE=' . $this->ButtonSource; $this->NVPCredentials .= $this->APISubject != '' ? '&SUBJECT=' . $this->APISubject : ''; $this->NVPCredentials .= $this->APIMode == 'Signature' ? '&SIGNATURE=' . $this->APISignature : ''; @@ -2908,7 +2906,7 @@ function BMCreateButton($DataArray) $n = 0; $BMButtonVars = isset($DataArray['BMButtonVars']) ? $DataArray['BMButtonVars'] : array(); - $BMButtonVars['bn'] = $this->APIButtonSource; + $BMButtonVars['bn'] = $this->ButtonSource; foreach ($BMButtonVars as $BMButtonVarName => $BMButtonVarValue) { $BMCreateButtonNVP .= $BMButtonVarValue != '' ? "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue) : ""; if ($BMButtonVarValue != '') { @@ -2967,7 +2965,7 @@ function BMUpdateButton($DataArray) $n = 0; $BMButtonVars = isset($DataArray['BMButtonVars']) ? $DataArray['BMButtonVars'] : array(); - $BMButtonVars['bn'] = $this->APIButtonSource; + $BMButtonVars['bn'] = $this->ButtonSource; foreach ($BMButtonVars as $BMButtonVarName => $BMButtonVarValue) { $BMUpdateButtonNVP .= $BMButtonVarValue != '' ? "&L_BUTTONVAR" . $n . "=" . urlencode($BMButtonVarName . "=" . $BMButtonVarValue) : ""; if ($BMButtonVarValue != '') { From 2b962179eaeae35ab4887db263594d708d61cbd0 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 29 Dec 2025 18:22:35 +0530 Subject: [PATCH 063/146] Structurize Demo Folder and Update Index File --- demo/assets/css/style.css | 9 + .../DoExpressCheckoutPayment.php | 4 +- .../GetExpressCheckoutDetails.php | 4 +- .../SetExpressCheckout.php | 8 +- .../express-checkout-basic/index.php | 26 +- .../express-checkout-basic/order-complete.php | 22 +- .../express-checkout-basic/review.php | 22 +- demo/index.php | 476 +++--------------- .../PayPal/PayPalCommonFunctions.php | 2 +- 9 files changed, 122 insertions(+), 451 deletions(-) rename demo/{classic => }/express-checkout-basic/DoExpressCheckoutPayment.php (98%) rename demo/{classic => }/express-checkout-basic/GetExpressCheckoutDetails.php (99%) rename demo/{classic => }/express-checkout-basic/SetExpressCheckout.php (89%) rename demo/{classic => }/express-checkout-basic/index.php (87%) rename demo/{classic => }/express-checkout-basic/order-complete.php (88%) rename demo/{classic => }/express-checkout-basic/review.php (88%) diff --git a/demo/assets/css/style.css b/demo/assets/css/style.css index 3ec3429c..f263bdb6 100755 --- a/demo/assets/css/style.css +++ b/demo/assets/css/style.css @@ -27,6 +27,9 @@ border-left: 4px solid #F0C100; margin-top: 20px; } +.warning-info.demo-warning-info { + margin-top: 0; +} .warning-info .warning-icon { display: flex; align-items: center; @@ -45,6 +48,9 @@ gap: 10px; margin: 20px 0; } +.main-title.demo-title { + justify-content: flex-start; +} .main-title img { width: 32px; height: 32px; @@ -53,6 +59,9 @@ font-size: 16px; margin-bottom: 20px; } +.main-info p { + margin-bottom: 4px; +} .demo-cred { background: #EFF6FF; padding: 24px; diff --git a/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php b/demo/express-checkout-basic/DoExpressCheckoutPayment.php similarity index 98% rename from demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php rename to demo/express-checkout-basic/DoExpressCheckoutPayment.php index b36744a9..6fc2eaaf 100644 --- a/demo/classic/express-checkout-basic/DoExpressCheckoutPayment.php +++ b/demo/express-checkout-basic/DoExpressCheckoutPayment.php @@ -2,8 +2,8 @@ /** * Include our config file and the PayPal library. */ -require_once('../../../includes/config.php'); -require_once('../../../vendor/autoload.php'); +require_once('../../includes/config.php'); +require_once('../../vendor/autoload.php'); /** * Setup configuration for the PayPal library using vars from the config file. diff --git a/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php b/demo/express-checkout-basic/GetExpressCheckoutDetails.php similarity index 99% rename from demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php rename to demo/express-checkout-basic/GetExpressCheckoutDetails.php index ba1f70f9..3502ce87 100644 --- a/demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php +++ b/demo/express-checkout-basic/GetExpressCheckoutDetails.php @@ -2,8 +2,8 @@ /** * Include our config file and the PayPal library. */ -require_once('../../../includes/config.php'); -require_once('../../../vendor/autoload.php'); +require_once('../../includes/config.php'); +require_once('../../vendor/autoload.php'); /** * Setup configuration for the PayPal library using vars from the config file. diff --git a/demo/classic/express-checkout-basic/SetExpressCheckout.php b/demo/express-checkout-basic/SetExpressCheckout.php similarity index 89% rename from demo/classic/express-checkout-basic/SetExpressCheckout.php rename to demo/express-checkout-basic/SetExpressCheckout.php index 05a9949e..99b2bab4 100644 --- a/demo/classic/express-checkout-basic/SetExpressCheckout.php +++ b/demo/express-checkout-basic/SetExpressCheckout.php @@ -2,8 +2,8 @@ /** * Include our config file and the PayPal library. */ -require_once('../../../includes/config.php'); -require_once('../../../vendor/autoload.php'); +require_once('../../includes/config.php'); +require_once('../../vendor/autoload.php'); /** * Setup configuration for the PayPal library using vars from the config file. @@ -34,8 +34,8 @@ */ $SECFields = array( 'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), // The expected maximum total amount the order will be, including S&H and sales tax. - 'returnurl' => $domain . 'demo/classic/express-checkout-basic/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. - 'cancelurl' => $domain . 'demo/classic/express-checkout-basic/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'returnurl' => $domain . 'demo/express-checkout-basic/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => $domain . 'demo/express-checkout-basic/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. 'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. 'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', // A URL to your logo image. Formats: .gif, .jpg, .png. 190x60. PayPal places your logo image at the top of the cart review area. This logo needs to be stored on a https:// server. 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. diff --git a/demo/classic/express-checkout-basic/index.php b/demo/express-checkout-basic/index.php similarity index 87% rename from demo/classic/express-checkout-basic/index.php rename to demo/express-checkout-basic/index.php index d8c5a841..dc7e3969 100644 --- a/demo/classic/express-checkout-basic/index.php +++ b/demo/express-checkout-basic/index.php @@ -1,6 +1,6 @@ - + - - - - - + + + + + - + @@ -88,10 +88,10 @@
@@ -99,7 +99,7 @@ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features.
-

CartShopping Cart

+

CartShopping Cart

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal after the user logs in and is returned back to the site.

diff --git a/demo/classic/express-checkout-basic/order-complete.php b/demo/express-checkout-basic/order-complete.php similarity index 88% rename from demo/classic/express-checkout-basic/order-complete.php rename to demo/express-checkout-basic/order-complete.php index 6dccd738..e9553dbf 100644 --- a/demo/classic/express-checkout-basic/order-complete.php +++ b/demo/express-checkout-basic/order-complete.php @@ -1,5 +1,5 @@ @@ -15,22 +15,22 @@ - + - - - - - + + + + + - + @@ -39,10 +39,10 @@
diff --git a/demo/classic/express-checkout-basic/review.php b/demo/express-checkout-basic/review.php similarity index 88% rename from demo/classic/express-checkout-basic/review.php rename to demo/express-checkout-basic/review.php index daef1170..710817e7 100644 --- a/demo/classic/express-checkout-basic/review.php +++ b/demo/express-checkout-basic/review.php @@ -1,5 +1,5 @@ @@ -15,22 +15,22 @@ - + - - - - - + + + + + - + @@ -39,10 +39,10 @@
diff --git a/demo/index.php b/demo/index.php index 0b8d59a9..5e7af413 100755 --- a/demo/index.php +++ b/demo/index.php @@ -34,399 +34,62 @@
-
+ -

-

What is This?
- The class library comes with FREE, fully functional /samples and empty /templates ready for you to work - with. The demo kits - available here are more complete and tie together a number of APIs within a basic shopping cart - interface so that you can see how everything flows together.

-

How Does This Work?
- Checkout one of the FREE demo kits included by clucking the Launch button. This will allow you - see an example of how the demo kits work. -

The HTML and code has lots of comments explaining - what is going - on so that you can see it for yourself, and learn from it. -

Additional demo kits are available - for purchase and can be installed here to complete your collection. -

-
-
-
-

REST API

-
-
- -
-
-

API v2

-
-
-
- -
-
-
Express Checkout Basic -
-

PayPal Checkout

-

w/ Line Items

-

Learn how to integrate PayPal Checkout w/ Line Items using PayPal's REST API v2. - It allows you to create and capture an order using the Orders API.

- -

- - Launch Demo - - Buy Now - -

-
-
-
-
-
Express Checkout Smart Payment Buttons Client Side - -
-

PayPal Checkout Smart Payment Buttons Client Side

-

Learn how to integrate PayPal Checkout using PayPal's javascript SDK. This code runs client side and - always keeps you current with the latest button styles and payment features.

-

- - Launch Demo - - Buy Now - -

-
-
-
-
-
Express Checkout Smart Payment Buttons Server Side - -
-

PayPal Checkout Smart Payment Buttons Server Side

-

Learn how to integrate PayPal Checkout using PayPal's javascript SDK. This code runs server side by making an ajax call and - always keeps you current with the latest button styles and payment features.

-

- - Launch Demo - - Buy Now - -

-
-
-
-
-
- -
-
-

API v1

-
-
-
-
-
-
Express Checkout Basic -
-

PayPal Checkout

-

w/ Line Items

-

Learn how to integrate PayPal Checkout w/ Line Items using PayPal's REST API. It allows you to create and execute payments using the REST API.

- -

- - Launch Demo - - Buy Now - -

-
-
-
-
-
Express Checkout Smart Payment Buttons Client Side - -
-

Checkout Smart Payment Buttons Client Side

-

Learn how to integrate PayPal Checkout using the checkout.js JavaScript code. This code - always keeps you current with the latest button styles and payment features.

-

- - Launch Demo - - Buy Now - -

-
-
-
-
-
Express Checkout Smart Payment Buttons Server Side - -
-

PayPal Checkout Smart Payment Buttons Server Side

-

Learn how to integrate PayPal Checkout using the checkout.js JavaScript code. This code - always keeps you current with the latest button styles and payment features.

-

- - Launch Demo - - Buy Now - -

-
-
-
- -
-
- -
-
Express Checkout Smart Payment Buttons Server Side - -
-

PayPal Checkout Billing Agreement

-

Payments API

-

Learn how to Use billing plans and billing agreements to create an agreement for a recurring PayPal payments for goods or services.

-

- - Launch Demo - - Buy Now - -

-
+
- -
-
PayPal Identity (Log In with PayPal) - -
-

PayPal Identity

-

Log In with PayPal - Basic Scope

-

Log In with PayPal (formerly PayPal Access) is a commerce identity solution that enables - your customers to sign in to your web site quickly and securely by using their PayPal - login credentials.

-

- - Launch Demo - - Buy Now - -

-
-
-
-
-
PayPal Identity + Grant API Permissions - -
-

PayPal Identity

-

Grant API Permissions

-

Log In with PayPal (formerly PayPal Access) is a commerce identity solution that enables - your customers to sign in to your web site quickly and securely by using their PayPal - login credentials.

-

- - Launch Demo - - Buy Now - -

-
+
+
-
-
-
Express Checkout Smart Payment Buttons Server Side - -
-

Create Payment

-

Direct Credit Card

-

Learn how to create a payment using direct credit card processing.

-

- - Launch Demo - - Buy Now - -

-
-
-
- -
-
Store CreditCard in PayPal Vault - -
-

PayPal Vault

-

Save Credit Card on File

-

Learn how to use the PayPal Vault API to securely store customer credit cards rather than on your server.

-

- - Launch Demo - - Buy Now - -

-
-
-
- -
-
Create Payment Using Saved Card - Vault - -
-

Token Payment (Reference Transaction)

-

Pay with Vaulted Card

-

Learn how to process a payment using a saved (vaulted) card in PayPal.

-

- - Launch Demo - - Buy Now - -

-
-
-
- +

DemoKits

+
+

What is This?

+

The class library comes with FREE, fully functional /samples and empty /templates ready for you to work with. The demo kits available here are more complete and tie together a number of APIs within a basic shopping cart interface so that you can see how everything flows together.

-
-
-
Create & Send Third Party Invoice PayPal -
-

Create & Send Invoice

-

3rd Party User

-

Learn how to create and send a PayPal Invoice on behalf of a third party user.

- -

- - Launch Demo - - Buy Now - -

-
-
-
+
+

How Does This Work?

+

Checkout one of the FREE demo kits included by clucking the Launch button. This will allow you see an example of how the demo kits work.

+

The HTML and code has lots of comments explaining what is going on so that you can see it for yourself, and learn from it.

+

+ Additional demo kits + are available for purchase and can be installed here to complete your collection. +

-

Classic API

-

Important Note

- The classic API is still available, but is being labeled as deprecated. You can still use them, and they work very well, but if you are starting fresh you may want to look at REST instead. +
+ !The classic API is still available, but is being labeled as deprecated. You can still use them, and they work very well, but if you are starting fresh you may want to look at REST instead. +

-
PayPal Express Checkout Basic Integration +
+ PayPal Express Checkout Basic Integration

Express Checkout

Basic

Here we are integrating Express Checkout without any line item details or any extra features. We obtain the user's shipping information so that we can calculate shipping and tax, but otherwise no additional data is included with this checkout demo.

-

Launch Demo +

Launch Demo

-
PayPal Express Checkout Line Items Integration +
+ PayPal Express Checkout Line Items Integration
@@ -437,7 +100,7 @@ interface so that you can see how everything flows together.

transaction details.

- Launch Demo + Launch Demo

-
PayPal Express Checkout Digital Goods Integration +
+ PayPal Express Checkout Digital Goods Integration
-
Express Checkout Billing Agreement +
-
Express Checkout Parallel Payments +
-
Express checkout 3rd Party No Permissions +
+ Express checkout 3rd Party No Permissions
-
Express Checkout In-Context +
-
Express Checkout Recurring Payment +
-
Express Checkout Shipped Items + Recurring Payment +
+ Express Checkout Shipped Items + Recurring Payment
@@ -606,7 +269,7 @@ interface so that you can see how everything flows together.

Launch Demo + href="express-checkout-shipped-items-recurring-payments/" target="_blank">Launch Demo

-
PayPal Payments Pro PayFlow Basic Integration +
-
PayPal Payments Pro PayFlow Recurring Billing Integration +
+ PayPal Payments Pro PayFlow Recurring Billing Integration
- Website Payments Pro 3.0 - DoDirectPayment + Website Payments Pro 3.0 - DoDirectPayment
@@ -684,7 +346,7 @@ interface so that you can see how everything flows together.

background.

- Launch Demo + Launch Demo async function initPayPalV6() { - const res = await fetch('../../../src/angelleye/PayPal/api/token.php'); + const res = await fetch('../../src/angelleye/PayPal/api/token.php'); const { token } = await res.json(); await paypal.createInstance({ From 594a19466d0abf26eaf053498d30f4a41f02b08d Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 30 Dec 2025 15:09:37 +0530 Subject: [PATCH 064/146] Updated Slug for the Express Checkout Basic --- demo/index.php | 5 +++-- .../DoExpressCheckoutPayment.php | 0 .../GetExpressCheckoutDetails.php | 0 .../SetExpressCheckout.php | 4 ++-- .../index.php | 0 .../order-complete.php | 0 .../review.php | 0 7 files changed, 5 insertions(+), 4 deletions(-) rename demo/{express-checkout-basic => paypal-checkout-basic}/DoExpressCheckoutPayment.php (100%) rename demo/{express-checkout-basic => paypal-checkout-basic}/GetExpressCheckoutDetails.php (100%) rename demo/{express-checkout-basic => paypal-checkout-basic}/SetExpressCheckout.php (91%) rename demo/{express-checkout-basic => paypal-checkout-basic}/index.php (100%) rename demo/{express-checkout-basic => paypal-checkout-basic}/order-complete.php (100%) rename demo/{express-checkout-basic => paypal-checkout-basic}/review.php (100%) diff --git a/demo/index.php b/demo/index.php index 5e7af413..bb5589c1 100755 --- a/demo/index.php +++ b/demo/index.php @@ -75,12 +75,13 @@

diff --git a/demo/express-checkout-basic/DoExpressCheckoutPayment.php b/demo/paypal-checkout-basic/DoExpressCheckoutPayment.php similarity index 100% rename from demo/express-checkout-basic/DoExpressCheckoutPayment.php rename to demo/paypal-checkout-basic/DoExpressCheckoutPayment.php diff --git a/demo/express-checkout-basic/GetExpressCheckoutDetails.php b/demo/paypal-checkout-basic/GetExpressCheckoutDetails.php similarity index 100% rename from demo/express-checkout-basic/GetExpressCheckoutDetails.php rename to demo/paypal-checkout-basic/GetExpressCheckoutDetails.php diff --git a/demo/express-checkout-basic/SetExpressCheckout.php b/demo/paypal-checkout-basic/SetExpressCheckout.php similarity index 91% rename from demo/express-checkout-basic/SetExpressCheckout.php rename to demo/paypal-checkout-basic/SetExpressCheckout.php index 99b2bab4..7c9c8ccf 100644 --- a/demo/express-checkout-basic/SetExpressCheckout.php +++ b/demo/paypal-checkout-basic/SetExpressCheckout.php @@ -34,8 +34,8 @@ */ $SECFields = array( 'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), // The expected maximum total amount the order will be, including S&H and sales tax. - 'returnurl' => $domain . 'demo/express-checkout-basic/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. - 'cancelurl' => $domain . 'demo/express-checkout-basic/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'returnurl' => $domain . 'demo/paypal-checkout-basic/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => $domain . 'demo/paypal-checkout-basic/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. 'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. 'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', // A URL to your logo image. Formats: .gif, .jpg, .png. 190x60. PayPal places your logo image at the top of the cart review area. This logo needs to be stored on a https:// server. 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. diff --git a/demo/express-checkout-basic/index.php b/demo/paypal-checkout-basic/index.php similarity index 100% rename from demo/express-checkout-basic/index.php rename to demo/paypal-checkout-basic/index.php diff --git a/demo/express-checkout-basic/order-complete.php b/demo/paypal-checkout-basic/order-complete.php similarity index 100% rename from demo/express-checkout-basic/order-complete.php rename to demo/paypal-checkout-basic/order-complete.php diff --git a/demo/express-checkout-basic/review.php b/demo/paypal-checkout-basic/review.php similarity index 100% rename from demo/express-checkout-basic/review.php rename to demo/paypal-checkout-basic/review.php From a6c32176d8b10e6a8d46c8c9f76087787a4063d7 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 30 Dec 2025 19:02:57 +0530 Subject: [PATCH 065/146] PayPal Checkout with Line Items Completed --- demo/index.php | 6 +- .../SetExpressCheckout.php | 21 ++ demo/paypal-checkout-basic/index.php | 205 ++++++++------- demo/paypal-checkout-basic/order-complete.php | 240 +++++++++--------- demo/paypal-checkout-basic/review.php | 231 +++++++++-------- .../DoExpressCheckoutPayment.php | 165 ++++++++++++ .../GetExpressCheckoutDetails.php | 237 +++++++++++++++++ .../SetExpressCheckout.php | 146 +++++++++++ demo/paypal-checkout-line-items/index.php | 172 +++++++++++++ .../order-complete.php | 141 ++++++++++ demo/paypal-checkout-line-items/review.php | 138 ++++++++++ 11 files changed, 1357 insertions(+), 345 deletions(-) create mode 100644 demo/paypal-checkout-line-items/DoExpressCheckoutPayment.php create mode 100644 demo/paypal-checkout-line-items/GetExpressCheckoutDetails.php create mode 100644 demo/paypal-checkout-line-items/SetExpressCheckout.php create mode 100644 demo/paypal-checkout-line-items/index.php create mode 100644 demo/paypal-checkout-line-items/order-complete.php create mode 100644 demo/paypal-checkout-line-items/review.php diff --git a/demo/index.php b/demo/index.php index bb5589c1..6ed28155 100755 --- a/demo/index.php +++ b/demo/index.php @@ -90,18 +90,18 @@
PayPal Express Checkout Line Items Integration
-

Express Checkout

+

PayPal Checkout

w/ Line Items

Here we expand on our basic Express Checkout demo to add individual order items to the API requests so that the data is available within PayPal's checkout review pages transaction details.

- Launch Demo + Launch Demo SetExpressCheckout($PayPalRequestData); +/** + * Based on the selected API mode, extract the appropriate redirect URL + * and order identifier from the SetExpressCheckout response. + * + * - For REST mode (when API upgrade is disabled), PayPal returns an + * `approval_url` for redirection and an `order_id` to track the transaction. + * - For Classic mode (or when API upgrade is enabled), PayPal returns a + * `REDIRECTURL` for redirection and a `TOKEN` that represents the checkout session. + * + * These values are normalized into $redirect_url and $orderId so the + * remaining flow can work consistently regardless of API mode. + */ $redirect_url = ''; if( $api_mode === 'rest' && !$api_upgrade ) { $redirect_url = $PayPalResult['approval_url']; @@ -93,6 +105,15 @@ $orderId = $PayPalResult['TOKEN']; } +/** + * Now we'll check for any errors returned by PayPal, and if we get an error, + * we'll save the error details to a session and redirect the user to an + * error page to display it accordingly. + * + * If all goes well, we save our token in a session variable so that it's + * readily available for us later, and then redirect the user to PayPal + * using the REDIRECTURL returned by the SetExpressCheckout() function. + */ if($redirect_url) { $_SESSION['paypal_token'] = $orderId; header('Location: ' . $redirect_url); diff --git a/demo/paypal-checkout-basic/index.php b/demo/paypal-checkout-basic/index.php index dc7e3969..cff16e3e 100644 --- a/demo/paypal-checkout-basic/index.php +++ b/demo/paypal-checkout-basic/index.php @@ -49,122 +49,119 @@ $_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'],2); ?> - - -PayPal Express Checkout Basic Demo | PHP Class Library | Angell EYE - - - + + + PayPal Express Checkout Basic Demo | PHP Class Library | Angell EYE + + + - - - - + + + + - - + + - - + + - - - - - - - - - - - - - - -

-
-
- - -
- !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. -
- -

CartShopping Cart

-

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any - billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal - after the user logs in and is returned back to the site.

-
-

Demo Credentials

-

Email: paypal-buyer@angelleye.com

-

Password: paypalphp

-
- - - - - - - - - - - - - - - - - - - - - -
IDNamePriceQTYTotal
$ $
+ + + + + + + + + + + + + +
-
-
-
- - - - - - - - - - - - - - - - - - +
+ + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

CartShopping Cart

+

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal after the user logs in and is returned back to the site.

+
+

Demo Credentials

+

Email: paypal-buyer@angelleye.com

+

Password: paypalphp

+
+
Subtotal$
Shipping$
Handling$
Tax$
+ - - + + + + + + + + - + + + + + +
Grand Total$IDNamePriceQTYTotal
renderPayPalButton(); ?> $ $
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
renderPayPalButton(); ?>
+
+
-
-
- + \ No newline at end of file diff --git a/demo/paypal-checkout-basic/order-complete.php b/demo/paypal-checkout-basic/order-complete.php index e9553dbf..0dd8fcfa 100644 --- a/demo/paypal-checkout-basic/order-complete.php +++ b/demo/paypal-checkout-basic/order-complete.php @@ -2,139 +2,137 @@ require_once('../../includes/config.php'); ?> - - -PayPal Express Checkout Basic Demo | Order Complete | PHP Class Library | Angell EYE - - - + + + PayPal Express Checkout Basic Demo | Order Complete | PHP Class Library | Angell EYE + + + - - - - + + + + - - + + - - + + - - - - - - - - - - - - -
-
-
- - -
- !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. -
- -

Payment Complete!

-

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID - to the Billing Information, which was provided in the DoExpressCheckoutPayment response.

- - - - - - - - - - - - - - - - - - - - - -
IDNamePriceQTYTotal
$ $
+ + + + + + + + + + + +
-
-

Billing Information

-

- ' . - $_SESSION['email'] . '
'. - $_SESSION['phone_number'] . '
' . - $_SESSION['paypal_transaction_id']; - ?> -

-
-
-

Shipping Information

-

- ' . - $_SESSION['shipping_street'] . '
' . - $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . - $_SESSION['shipping_country_name']; - ?> -

-
-
- - +
+ + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

Payment Complete!

+

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID to the Billing Information, which was provided in the DoExpressCheckoutPayment response.

+
+ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
 IDNamePriceQTYTotal
$ $
+
+
+

Billing Information

+

+ ' . + $_SESSION['email'] . '
'. + $_SESSION['phone_number'] . '
' . + $_SESSION['paypal_transaction_id']; + ?> +

+
+
+

Shipping Information

+

+ ' . + $_SESSION['shipping_street'] . '
' . + $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . + $_SESSION['shipping_country_name']; + ?> +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
 
+
+
-
-
- + - - -PayPal Express Checkout Basic Demo | Order Review | PHP Class Library | Angell EYE - - - + + + PayPal Express Checkout Basic Demo | Order Review | PHP Class Library | Angell EYE + + + - - - - + + + + - - + + - - + + - - - - - - - - - - - - -
-
-
- - -
- !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. -
- -

Order Review

-

Here we display a final review to the buyer now that we've calculated shipping, handling, and tax. The - billing and shipping information provided here is what we obtained in the GetExpressCheckoutDetails response.

-

The payment has not been processed at this point because we have not yet called the final DoExpressCheckoutPayment API. That is what will - happen when we click the "Complete Order" button below.

- - - - - - - - - - - - - - - - - - - - - -
IDNamePriceQTYTotal
$ $
+ + + + + + + + + + + +
-
-

Billing Information

-

- ' . - $_SESSION['email'] . '
'. - $_SESSION['phone_number'] . '
'; - ?> -

-
-
-

Shipping Information

-

- ' . - $_SESSION['shipping_street'] . '
' . - $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . - $_SESSION['shipping_country_name']; - ?> -

-
-
- - - - - - - - - - - - - - - - - - +
+ + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

Order Review

+

Here we display a final review to the buyer now that we've calculated shipping, handling, and tax. The billing and shipping information provided here is what we obtained in the GetExpressCheckoutDetails response.

+

The payment has not been processed at this point because we have not yet called the final DoExpressCheckoutPayment API. That is what will happen when we click the "Complete Order" button below.

+
Subtotal$
Shipping$
Handling$
Tax$
+ - - + + + + + + + + - + + + + + +
Grand Total$IDNamePriceQTYTotal
Complete Order $ $
+
+
+

Billing Information

+

+ ' . + $_SESSION['email'] . '
'. + $_SESSION['phone_number'] . '
'; + ?> +

+
+
+

Shipping Information

+

+ ' . + $_SESSION['shipping_street'] . '
' . + $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . + $_SESSION['shipping_country_name']; + ?> +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
Complete Order
+
+
-
-
- + \ No newline at end of file diff --git a/demo/paypal-checkout-line-items/DoExpressCheckoutPayment.php b/demo/paypal-checkout-line-items/DoExpressCheckoutPayment.php new file mode 100644 index 00000000..9255ea92 --- /dev/null +++ b/demo/paypal-checkout-line-items/DoExpressCheckoutPayment.php @@ -0,0 +1,165 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +/** + * Now we'll setup the request params for the final call in the Express Checkout flow. + * This is very similar to SetExpressCheckout except that now we can include values + * for the shipping, handling, and tax amounts, as well as the buyer's name and + * shipping address that we obtained in the GetExpressCheckoutDetails step. + * + * If this information is not included in this final call, it will not be + * available in PayPal's transaction details data. + * + * Once again, the template for DoExpressCheckoutPayment provides + * many more params that are available, but we've stripped everything + * we are not using in this basic demo out. + */ +$DECPFields = array( + 'token' => $_SESSION['paypal_token'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. + 'payerid' => $_SESSION['paypal_payer_id'], // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. +); + +/** + * Just like with SetExpressCheckout, we need to gather our $Payment + * data to pass into our $Payments array. This time we can include + * the shipping, handling, tax, and shipping address details that we + * now have. + */ +$Payments = array(); +$Payment = array( + 'amt' => number_format($_SESSION['shopping_cart']['grand_total'],2), // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'itemamt' => number_format($_SESSION['shopping_cart']['subtotal'],2), // Subtotal of items only. + 'currencycode' => 'USD', // A three-character currency code. Default is USD. + 'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'],2), // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'handlingamt' => number_format($_SESSION['shopping_cart']['handling'],2), // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => number_format($_SESSION['shopping_cart']['tax'],2), // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'shiptoname' => $_SESSION['shipping_name'], // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => $_SESSION['shipping_street'], // Required if shipping is included. First street address. 100 char max. + 'shiptocity' => $_SESSION['shipping_city'], // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => $_SESSION['shipping_state'], // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => $_SESSION['shipping_zip'], // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountrycode' => $_SESSION['shipping_country_code'], // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => $_SESSION['phone_number'], // Phone number for shipping address. 20 char max. + 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. +); + +/** + * Here we'll begin creating our order items that belong to this $Payment in the request. + * We will loop through the items in our shopping cart to add them each into our + * $Payment. + */ +$PaymentOrderItems = array(); +foreach ($_SESSION['shopping_cart']['items'] as $cart_item) { + $Item = array( + 'name' => $cart_item['name'], // Item name. 127 char max. + 'amt' => $cart_item['price'], // Cost of item. + 'number' => $cart_item['id'], // Item number. 127 char max. + 'qty' => $cart_item['qty'], // Item qty on order. Any positive integer. + ); + array_push($PaymentOrderItems, $Item); +} + +/** + * Now that $PaymentOrderItems is filled with all of our shopping cart items, + * we'll add that to our $Payment array. + */ +$Payment['order_items'] = $PaymentOrderItems; + +/** + * Here we push our single $Payment into our $Payments array. + */ +array_push($Payments, $Payment); + +/** + * Now we gather all of the arrays above into a single array. + */ +$PayPalRequestData = array( + 'DECPFields' => $DECPFields, + 'Payments' => $Payments, +); + +/** + * Here we are making the call to the DoExpressCheckoutPayment function in the library, + * and we're passing in our $PayPalRequestData that we just set above. + */ +$PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData); + +/** + * Now we'll check for any errors returned by PayPal, and if we get an error, + * we'll save the error details to a session and redirect the user to an + * error page to display it accordingly. + * + * If the call is successful, we'll save some data we might want to use + * later into session variables, and then redirect to our final + * thank you / receipt page. + */ +if( $api_mode === 'classic' && $PayPal->APICallSuccessful($PayPalResult['ACK']) ) { + /** + * Once again, since Express Checkout allows for multiple payments in a single transaction, + * the DoExpressCheckoutPayment response is setup to provide data for each potential payment. + * As such, we need to loop through all the payment info in the response. + * + * The library helps us do this using the GetExpressCheckoutPaymentInfo() method. We'll + * load our $payments_info using that method, and then loop through the results to pull + * out our details for the transaction. + * + * Again, in this case we are you only working with a single payment, but we'll still + * loop through the results accordingly. + * + * Here, we're only pulling out the PayPal transaction ID and fee amount, but you may + * refer to the API reference for all the additional parameters you have available at + * this point. + * + * https://developer.paypal.com/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/ + */ + $payments_info = $PayPal->GetExpressCheckoutPaymentInfo($PayPalResult); + + foreach($payments_info as $payment_info) + { + $_SESSION['paypal_transaction_id'] = isset($payment_info['TRANSACTIONID']) ? $payment_info['TRANSACTIONID'] : ''; + $_SESSION['paypal_fee'] = isset($payment_info['FEEAMT']) ? $payment_info['FEEAMT'] : ''; + } + + header('Location: order-complete.php'); +} elseif( $api_mode === 'rest' && $PayPalResult['success'] ) { + $_SESSION['paypal_transaction_id'] = isset( $PayPalResult['capture_id'] ) ? $PayPalResult['capture_id'] : ''; + + $captures = ( $PayPalResult['purchase_units'][0]['payments']['captures'][0] ) ? $PayPalResult['purchase_units'][0]['payments']['captures'][0] : []; + $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; + + header('Location: order-complete.php'); +} elseif( $api_mode === 'rest' && $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' ) { + $payments_info = isset( $PayPalResult['PAYMENTS'][0] ) ? $PayPalResult['PAYMENTS'][0] : []; + + $_SESSION['paypal_transaction_id'] = isset($payments_info['TRANSACTIONID']) ? $payments_info['TRANSACTIONID'] : ''; + $_SESSION['paypal_fee'] = isset($payments_info['FEEAMT']) ? $payments_info['FEEAMT'] : '0.00'; + + header('Location: order-complete.php'); +} else { + $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; + header('Location: ../../error.php'); +} \ No newline at end of file diff --git a/demo/paypal-checkout-line-items/GetExpressCheckoutDetails.php b/demo/paypal-checkout-line-items/GetExpressCheckoutDetails.php new file mode 100644 index 00000000..b2599f00 --- /dev/null +++ b/demo/paypal-checkout-line-items/GetExpressCheckoutDetails.php @@ -0,0 +1,237 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + + +$DECPFields = array( + 'token' => $_SESSION['paypal_token'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. + 'payerid' => '', // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. +); + +/** + * Just like with SetExpressCheckout, we need to gather our $Payment + * data to pass into our $Payments array. This time we can include + * the shipping, handling, tax, and shipping address details that we + * now have. + */ +$Payments = array(); +$Payment = array( + 'amt' => number_format($_SESSION['shopping_cart']['grand_total'],2), // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'itemamt' => number_format($_SESSION['shopping_cart']['subtotal'],2), // Subtotal of items only. + 'currencycode' => 'USD', // A three-character currency code. Default is USD. + 'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'],2), // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. + 'handlingamt' => number_format($_SESSION['shopping_cart']['handling'],2), // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. + 'taxamt' => number_format($_SESSION['shopping_cart']['tax'],2), // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. + 'shiptoname' => $_SESSION['shipping_name'], // Required if shipping is included. Person's name associated with this address. 32 char max. + 'shiptostreet' => $_SESSION['shipping_street'], // Required if shipping is included. First street address. 100 char max. + 'shiptocity' => $_SESSION['shipping_city'], // Required if shipping is included. Name of city. 40 char max. + 'shiptostate' => $_SESSION['shipping_state'], // Required if shipping is included. Name of state or province. 40 char max. + 'shiptozip' => $_SESSION['shipping_zip'], // Required if shipping is included. Postal code of shipping address. 20 char max. + 'shiptocountrycode' => $_SESSION['shipping_country_code'], // Required if shipping is included. Country code of shipping address. 2 char max. + 'shiptophonenum' => $_SESSION['phone_number'], // Phone number for shipping address. 20 char max. + 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. +); + +/** + * Here we'll begin creating our order items that belong to this $Payment in the request. + * We will loop through the items in our shopping cart to add them each into our + * $Payment. + */ +$PaymentOrderItems = array(); +foreach ($_SESSION['shopping_cart']['items'] as $cart_item) { + $Item = array( + 'name' => $cart_item['name'], // Item name. 127 char max. + 'amt' => $cart_item['price'], // Cost of item. + 'number' => $cart_item['id'], // Item number. 127 char max. + 'qty' => $cart_item['qty'], // Item qty on order. Any positive integer. + ); + array_push($PaymentOrderItems, $Item); +} + +/** + * Now that $PaymentOrderItems is filled with all of our shopping cart items, + * we'll add that to our $Payment array. + */ +$Payment['order_items'] = $PaymentOrderItems; + +/** + * Here we push our single $Payment into our $Payments array. + */ +array_push($Payments, $Payment); + +/** + * Now we gather all of the arrays above into a single array. + */ +$PayPalRequestData = array( + 'DECPFields' => $DECPFields, + 'Payments' => $Payments, +); + +/* + * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal + */ +if ( $api_mode === 'rest' ) { + $PayPalResult = $PayPal->GetExpressCheckoutDetails($PayPalRequestData); +} else { + $PayPalResult = $PayPal->GetExpressCheckoutDetails($_SESSION['paypal_token']); +} + +/** + * Now we'll check for any errors returned by PayPal, and if we get an error, + * we'll save the error details to a session and redirect the user to an + * error page to display it accordingly. + * + * If the call is successful, we'll save some data we might want to use + * later into session variables. + */ +if( $api_mode === 'classic' && $PayPal->APICallSuccessful($PayPalResult['ACK']) ) { + /** + * Here we'll pull out data from the PayPal response. + * Refer to the PayPal API Reference for all of the variables available + * in $PayPalResult['variablename'] + * + * https://developer.paypal.com/docs/classic/api/merchant/GetExpressCheckoutDetails_API_Operation_NVP/ + * + * Again, Express Checkout allows for parallel payments, so what we're doing here + * is usually the library to parse out the individual payments using the GetPayments() + * method so that we can easily access the data. + * + * We only have a single payment here, which will be the case with most checkouts, + * but we will still loop through the $Payments array returned by the library + * to grab our data accordingly. + */ + $_SESSION['paypal_payer_id'] = isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : ''; + $_SESSION['phone_number'] = isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : ''; + $_SESSION['email'] = isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : ''; + $_SESSION['first_name'] = isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : ''; + $_SESSION['last_name'] = isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : ''; + + $payments = $PayPal->GetPayments($PayPalResult); + + foreach($payments as $payment) + { + $_SESSION['shipping_name'] = isset($payment['SHIPTONAME']) ? $payment['SHIPTONAME'] : ''; + $_SESSION['shipping_street'] = isset($payment['SHIPTOSTREET']) ? $payment['SHIPTOSTREET'] : ''; + $_SESSION['shipping_city'] = isset($payment['SHIPTOCITY']) ? $payment['SHIPTOCITY'] : ''; + $_SESSION['shipping_state'] = isset($payment['SHIPTOSTATE']) ? $payment['SHIPTOSTATE'] : ''; + $_SESSION['shipping_zip'] = isset($payment['SHIPTOZIP']) ? $payment['SHIPTOZIP'] : ''; + $_SESSION['shipping_country_code'] = isset($payment['SHIPTOCOUNTRYCODE']) ? $payment['SHIPTOCOUNTRYCODE'] : ''; + $_SESSION['shipping_country_name'] = isset($payment['SHIPTOCOUNTRYNAME']) ? $payment['SHIPTOCOUNTRYNAME'] : ''; + } + + /** + * At this point, we now have the buyer's shipping address available in our app. + * We could now run the data through a shipping calculator to retrieve rate + * information for this particular order. + * + * This would also be the time to calculate any sales tax you may need to + * add to the order, as well as handling fees. + * + * We're going to set static values for these things in our static + * shopping cart, and then re-calculate our grand total. + */ + $_SESSION['shopping_cart']['shipping'] = 10.00; + $_SESSION['shopping_cart']['handling'] = 2.50; + $_SESSION['shopping_cart']['tax'] = 1.50; + + $_SESSION['shopping_cart']['grand_total'] = number_format( + $_SESSION['shopping_cart']['subtotal'] + + $_SESSION['shopping_cart']['shipping'] + + $_SESSION['shopping_cart']['handling'] + + $_SESSION['shopping_cart']['tax'],2); + + /** + * Now we will redirect the user to a final review + * page so they can see the shipping/handling/tax + * that has been added to the order. + */ + header('Location: review.php'); +} elseif( $api_mode === 'rest' && ($PayPalResult['success'] || ( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' )) ) { + /** + * Here we'll pull out data from the PayPal response. + */ + $_SESSION['paypal_payer_id'] = ( ! $api_upgrade ) + ? ( isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : '' ) + : ( isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : '' ); + $_SESSION['phone_number'] = ( ! $api_upgrade ) + ? ( isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : '' ) + : ( isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : '' ); + $_SESSION['email'] = ( ! $api_upgrade ) + ? ( isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : '' ) + : ( isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : '' ); + $_SESSION['first_name'] = ( ! $api_upgrade ) + ? ( isset($PayPalResult['order']['payer']['name']['given_name']) ? $PayPalResult['order']['payer']['name']['given_name'] : '' ) + : ( isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : '' ); + $_SESSION['last_name'] = ( ! $api_upgrade ) + ? ( isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : '' ) + : ( isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : '' ); + $_SESSION['billing_country_code'] = ( ! $api_upgrade ) + ? ( isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : '' ) + : ( isset($PayPalResult['COUNTRYCODE']) ? $PayPalResult['COUNTRYCODE'] : '' ); + + $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; + $shipping = ( ! $api_upgrade ) + ? ( isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : [] ) + : ( isset( $PayPalResult['SHIPPINGDATA'] ) ? $PayPalResult['SHIPPINGDATA'] : [] ); + $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; + $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; + $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; + $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; + $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; + $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; + $_SESSION['shipping_country_name'] = 'United States'; + + /** + * At this point, we now have the buyer's shipping address available in our app. + * We could now run the data through a shipping calculator to retrieve rate + * information for this particular order. + * + * This would also be the time to calculate any sales tax you may need to + * add to the order, as well as handling fees. + * + * We're going to set static values for these things in our static + * shopping cart, and then re-calculate our grand total. + */ + $_SESSION['shopping_cart']['shipping'] = 10.00; + $_SESSION['shopping_cart']['handling'] = 2.50; + $_SESSION['shopping_cart']['tax'] = 1.50; + + $_SESSION['shopping_cart']['grand_total'] = number_format( + $_SESSION['shopping_cart']['subtotal'] + + $_SESSION['shopping_cart']['shipping'] + + $_SESSION['shopping_cart']['handling'] + + $_SESSION['shopping_cart']['tax'],2); + + /** + * Now we will redirect the user to a final review + * page so they can see the shipping/handling/tax + * that has been added to the order. + */ + header('Location: review.php'); +} else { + $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; + header('Location: ../../error.php'); +} \ No newline at end of file diff --git a/demo/paypal-checkout-line-items/SetExpressCheckout.php b/demo/paypal-checkout-line-items/SetExpressCheckout.php new file mode 100644 index 00000000..f666e3d0 --- /dev/null +++ b/demo/paypal-checkout-line-items/SetExpressCheckout.php @@ -0,0 +1,146 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +/** + * Here we are setting up the parameters for a basic Express Checkout flow. + * + * The template provided at ../../vendor/angelleye/paypal-php-library/templates/SetExpressCheckout.php + * contains a lot more parameters that we aren't using here, so I've removed them to keep this clean. + * + * $domain used here is set in the config file. + */ +$SECFields = array( + 'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), // The expected maximum total amount the order will be, including S&H and sales tax. + 'returnurl' => $domain . 'demo/paypal-checkout-line-items/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. + 'cancelurl' => $domain . 'demo/paypal-checkout-line-items/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. + 'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. + 'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', // A URL to your logo image. Formats: .gif, .jpg, .png. 190x60. PayPal places your logo image at the top of the cart review area. This logo needs to be stored on a https:// server. + 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. + 'customerservicenumber' => '816-555-5555', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. +); + +/** + * Now we begin setting up our payment(s). + * + * Express Checkout includes the ability to setup parallel payments, + * so we have to populate our $Payments array here accordingly. + * + * For this sample (and in most use cases) we only need a single payment, + * but we still have to populate $Payments with a single $Payment array. + * + * Once again, the template file includes a lot more available parameters, + * but for this line items sample we've removed everything that we're not using. + */ +$Payments = array(); +$Payment = array( + 'amt' => $_SESSION['shopping_cart']['grand_total'], // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. + 'itemamt' => $_SESSION['shopping_cart']['subtotal'], // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. +); + +/** + * Here we'll begin creating our order items that belong to this $Payment in the request. + * We will loop through the items in our shopping cart to add them each into our + * $Payment. + */ +$PaymentOrderItems = array(); +foreach ($_SESSION['shopping_cart']['items'] as $cart_item) { + $Item = array( + 'name' => $cart_item['name'], // Item name. 127 char max. + 'amt' => $cart_item['price'], // Cost of item. + 'number' => $cart_item['id'], // Item number. 127 char max. + 'qty' => $cart_item['qty'], // Item qty on order. Any positive integer. + ); + array_push($PaymentOrderItems, $Item); +} + +/** + * Now that $PaymentOrderItems is filled with all of our shopping cart items, + * we'll add that to our $Payment array. + */ +$Payment['order_items'] = $PaymentOrderItems; + +/** + * Here we push our single $Payment into our $Payments array. + */ +array_push($Payments, $Payment); + +/** + * Now we gather all of the arrays above into a single array. + */ +$PayPalRequestData = array( + 'SECFields' => $SECFields, + 'Payments' => $Payments, +); + +/** + * Here we are making the call to the SetExpressCheckout function in the library, + * and we're passing in our $PayPalRequestData that we just set above. + */ +$PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData); + +/** + * Based on the selected API mode, extract the appropriate redirect URL + * and order identifier from the SetExpressCheckout response. + * + * - For REST mode (when API upgrade is disabled), PayPal returns an + * `approval_url` for redirection and an `order_id` to track the transaction. + * - For Classic mode (or when API upgrade is enabled), PayPal returns a + * `REDIRECTURL` for redirection and a `TOKEN` that represents the checkout session. + * + * These values are normalized into $redirect_url and $orderId so the + * remaining flow can work consistently regardless of API mode. + */ +$redirect_url = ''; +if( $api_mode === 'rest' && !$api_upgrade ) { + $redirect_url = $PayPalResult['approval_url']; +} else { + $redirect_url = $PayPalResult['REDIRECTURL']; +} + +$orderId = ''; +if( $api_mode === 'rest' && !$api_upgrade ) { + $orderId = $PayPalResult['order_id']; +} else { + $orderId = $PayPalResult['TOKEN']; +} + +/** + * Now we'll check for any errors returned by PayPal, and if we get an error, + * we'll save the error details to a session and redirect the user to an + * error page to display it accordingly. + * + * If all goes well, we save our token in a session variable so that it's + * readily available for us later, and then redirect the user to PayPal + * using the REDIRECTURL returned by the SetExpressCheckout() function. + */ +if($redirect_url) { + $_SESSION['paypal_token'] = $orderId; + header('Location: ' . $redirect_url); +} else { + $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; + header('Location: ../../error.php'); +} \ No newline at end of file diff --git a/demo/paypal-checkout-line-items/index.php b/demo/paypal-checkout-line-items/index.php new file mode 100644 index 00000000..45a94d87 --- /dev/null +++ b/demo/paypal-checkout-line-items/index.php @@ -0,0 +1,172 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, + 'APIUsername' => $api_username, + 'APIPassword' => $api_password, + 'APISignature' => $api_signature, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPalCommonFunctions = new angelleye\PayPal\PayPalCommonFunctions($PayPalConfig); + +/** + * Here we are building a very simple, static shopping cart to use + * throughout this demo. In most cases, you will working with a dynamic + * shopping cart system of some sort. + */ +$_SESSION['items'][0] = array( + 'id' => '123-ABC', + 'name' => 'Widget', + 'qty' => '2', + 'price' => '9.99', +); + +$_SESSION['items'][1] = array( + 'id' => 'XYZ-456', + 'name' => 'Gadget', + 'qty' => '1', + 'price' => '4.99', +); +$_SESSION['shopping_cart'] = array( + 'items' => $_SESSION['items'], + 'subtotal' => 24.97, + 'shipping' => 0, + 'handling' => 0, + 'tax' => 0, +); +$_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'], 2); +?> + + + + PayPal Express Checkout w/ Line Items Demo | PHP Class Library | Angell EYE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

CartShopping Cart

+

Here we are using a basic shopping cart for display purposes, and we are expanding on the basic demo to include the cart line items with the PayPal payment so that they will show up on the PayPal review pages during checkout and in the PayPal tranaction details. Again, we are assuming that we have not collected any billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal after the user logs in and is returned back to the site.

+
+

Demo Credentials

+

Email: paypal-buyer@angelleye.com

+

Password: paypalphp

+
+ + + + + + + + + + + + + + + + + + + + + +
IDNamePriceQTYTotal
$ $
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
renderPayPalButton(); ?>
+
+
+
+
+
+ + \ No newline at end of file diff --git a/demo/paypal-checkout-line-items/order-complete.php b/demo/paypal-checkout-line-items/order-complete.php new file mode 100644 index 00000000..f32ccc4e --- /dev/null +++ b/demo/paypal-checkout-line-items/order-complete.php @@ -0,0 +1,141 @@ + + + + + PayPal Express Checkout w/ Line Items Demo | Order Complete | PHP Class Library | Angell EYE + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

Payment Complete!

+

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID to the Billing Information, which was provided in the DoExpressCheckoutPayment response.

+ + + + + + + + + + + + + + + + + + + + + +
IDNamePriceQTYTotal
$ $
+
+
+

Billing Information

+

+ ' . + $_SESSION['email'] . '
' . + $_SESSION['phone_number'] . '
' . + $_SESSION['paypal_transaction_id']; + ?> +

+
+
+

Shipping Information

+

+ ' . + $_SESSION['shipping_street'] . '
' . + $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . + $_SESSION['shipping_country_name']; + ?> +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
 
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/demo/paypal-checkout-line-items/review.php b/demo/paypal-checkout-line-items/review.php new file mode 100644 index 00000000..1e204a3b --- /dev/null +++ b/demo/paypal-checkout-line-items/review.php @@ -0,0 +1,138 @@ + + + + + PayPal Express Checkout w/ Line Items Demo | Order Review | PHP Class Library | Angell EYE + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ !PayPal Classic API is deprecated. Please upgrade to the REST API for continued support and latest features. +
+ +

Order Review

+

Here we display a final review to the buyer now that we've calculated shipping, handling, and tax. The billing and shipping information provided here is what we obtained in the GetExpressCheckoutDetails response.

+

The payment has not been processed at this point because we have not yet called the final DoExpressCheckoutPayment API. That is what will happen when we click the "Complete Order" button below.

+ + + + + + + + + + + + + + + + + + + + + +
IDNamePriceQTYTotal
$ $
+
+
+

Billing Information

+

+ ' . + $_SESSION['email'] . '
' . + $_SESSION['phone_number'] . '
'; + ?> +

+
+
+

Shipping Information

+

+ ' . + $_SESSION['shipping_street'] . '
' . + $_SESSION['shipping_city'] . ', ' . $_SESSION['shipping_state'] . ' ' . $_SESSION['shipping_zip'] . '
' . + $_SESSION['shipping_country_name']; + ?> +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Subtotal$
Shipping$
Handling$
Tax$
Grand Total$
Complete Order
+
+
+
+
+
+ + \ No newline at end of file From c9e80225c15210df1388fd4e1ddd1182da0d550c Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Thu, 1 Jan 2026 17:04:57 +0530 Subject: [PATCH 066/146] Completed Recurring Subscriptions --- demo/error.php | 111 +-- demo/index.php | 667 +++++++++--------- .../DoExpressCheckoutPayment.php | 2 +- .../GetExpressCheckoutDetails.php | 2 +- .../SetExpressCheckout.php | 2 +- .../DoExpressCheckoutPayment.php | 2 +- .../GetExpressCheckoutDetails.php | 2 +- .../SetExpressCheckout.php | 2 +- .../CreateRecurringPaymentsProfile.php | 199 ++++++ .../GetExpressCheckoutDetails.php | 93 +++ .../GetRecurringPaymentsProfileDetails.php | 59 ++ .../SetExpressCheckout.php | 114 +++ demo/paypal-checkout-subscriptions/index.php | 150 ++++ .../order-complete.php | 105 +++ src/angelleye/PayPal/PayPalREST.php | 95 ++- 15 files changed, 1159 insertions(+), 446 deletions(-) create mode 100644 demo/paypal-checkout-subscriptions/CreateRecurringPaymentsProfile.php create mode 100644 demo/paypal-checkout-subscriptions/GetExpressCheckoutDetails.php create mode 100644 demo/paypal-checkout-subscriptions/GetRecurringPaymentsProfileDetails.php create mode 100644 demo/paypal-checkout-subscriptions/SetExpressCheckout.php create mode 100644 demo/paypal-checkout-subscriptions/index.php create mode 100644 demo/paypal-checkout-subscriptions/order-complete.php diff --git a/demo/error.php b/demo/error.php index f6e712d5..9122ffbd 100755 --- a/demo/error.php +++ b/demo/error.php @@ -17,67 +17,68 @@ $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); ?> - - -PayPal Demo Error | PHP Class Library | Angell EYE - - - + + + PayPal Demo Error | PHP Class Library | Angell EYE + + + - - - - + + + + - - + + - - + - - - - - - - - - - - - -
-
-
- -
- $value){ - echo ''.ucwords(str_replace('_',' ',$key)).' : '. $value.'
'; + + + + + + + + + + + +
+
+
+ +
+ $value){ + echo ''.ucwords(str_replace('_',' ',$key)).' : '. $value.'
'; + } + unset($_SESSION['rest_errors']); + } + elseif( $api_mode === 'rest' ) { + echo '
';
+            print_r($_SESSION['paypal_errors']);
+          } else {
+            $PayPal->DisplayErrors($_SESSION['paypal_errors']);
           }
-          unset($_SESSION['rest_errors']);
-      }
-      else{
-        $PayPal->DisplayErrors($_SESSION['paypal_errors']);
-      }
-	  ?>
+        ?>
+          
+
-
-
- + \ No newline at end of file diff --git a/demo/index.php b/demo/index.php index 6ed28155..4c53060d 100755 --- a/demo/index.php +++ b/demo/index.php @@ -1,363 +1,364 @@ - - - PayPal PHP Class Library Demo | PayPal Partner | Angell EYE - - - + + + PayPal PHP Class Library Demo | PayPal Partner | Angell EYE + + + - - - - + + + + - - + + - - + + - - - - - - - - - - - - -
-
-
- -
- - \ No newline at end of file From c969c4e0456e6de14049ccffb18ace27928a6714 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Sat, 14 Mar 2026 19:38:21 +0530 Subject: [PATCH 135/146] DirectPayment Changes --- .../DoDirectPayment.php | 224 ++++++++++-------- .../acdc.js | 20 +- .../getOrder.php | 26 +- .../guest-checkout.js | 20 +- .../index.php | 29 ++- .../order-complete.php | 2 +- 6 files changed, 163 insertions(+), 158 deletions(-) diff --git a/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php b/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php index df1ac426..b9b78756 100644 --- a/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php +++ b/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php @@ -2,116 +2,136 @@ require_once('../../includes/config.php'); require_once('../../autoload.php'); +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} + $PayPalConfig = array( 'Sandbox' => $sandbox, 'PayPalAPIMode' => $api_mode, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, 'PayPalAPIUpgrade' => $api_upgrade, 'ClientID' => $rest_client_id, 'ClientSecret' => $rest_client_secret, - 'MerchantID' => $rest_merchant_id + 'MerchantID' => $rest_merchant_id, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, ); $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); -$DPFields = array( - 'paymentaction' => 'Sale', // How you want to obtain payment. Authorization indicates the payment is a basic auth subject to settlement with Auth & Capture. Sale indicates that this is a final sale for which you are requesting payment. Default is Sale. - 'restintent' => 'CAPTURE', // REST only. Payment intent. Allowed values are: authorize, order, and capture. Default is capture. - 'ipaddress' => $_SERVER['REMOTE_ADDR'], // Required. IP address of the payer's browser. - 'returnfmfdetails' => '1' // Flag to determine whether you want the results returned by FMF. 1 or 0. Default is 0. -); - -$CCDetails = array( - 'creditcardtype' => $_SESSION['card_details']['creditcardtype'], // Required. Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. - 'acct' => $_SESSION['card_details']['accountnumber'], // Required. Credit card number. No spaces or punctuation. - 'expdate' => $_SESSION['card_details']['expiry'], // Required. Credit card expiration date. Format is MMYYYY - 'cvv2' => $_SESSION['card_details']['cvv'], // Requirements determined by your PayPal account settings. Security digits for credit card. - 'startdate' => '', // Month and year that Maestro or Solo card was issued. MMYYYY - 'issuenumber' => '' // Issue number of Maestro or Solo card. Two numeric digits max. -); - -$PayerInfo = array( - 'email' => $_SESSION['payer']['email'], // Email address of payer. - 'payerid' => '', // Unique PayPal customer ID for payer. - 'payerstatus' => '', // Status of payer. Values are verified or unverified - 'business' => '' // Payer's business name. -); - -$PayerName = array( - 'salutation' => '', // Payer's salutation. 20 char max. - 'firstname' => $_SESSION['payer']['firstname'], // Payer's first name. 25 char max. - 'middlename' => '', // Payer's middle name. 25 char max. - 'lastname' => $_SESSION['payer']['lastname'], // Payer's last name. 25 char max. - 'suffix' => '' // Payer's suffix. 12 char max. -); - -$BillingAddress = array( - 'street' => $_SESSION['billing']['street'], // Required. First street address. - 'street2' => '', // Second street address. - 'city' => $_SESSION['billing']['city'], // Required. Name of City. - 'state' => $_SESSION['billing']['state'], // Required. Name of State or Province. - 'countrycode' => $_SESSION['billing']['countrycode'], // Required. Country code. - 'zip' => $_SESSION['billing']['zip'], // Required. Postal code of payer. - 'phonenum' => $_SESSION['payer']['phonenumber'] // Phone Number of payer. 20 char max. -); - -$ShippingAddress = array( - 'shiptoname' => '', // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => '', // Required if shipping is included. First street address. 100 char max. - 'shiptostreet2' => '', // Second street address. 100 char max. - 'shiptocity' => '', // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => '', // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => '', // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountrycode' => '', // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => '' // Phone number for shipping address. 20 char max. -); - -$PaymentDetails = array( - 'amt' => $_SESSION['shopping_cart']['grand_total'], // Required. Total amount of order, including shipping, handling, and tax. - 'currencycode' => 'USD', // Required. Three-letter currency code. Default is USD. - 'itemamt' => '', // Required if you include itemized cart details. (L_AMTn, etc.) Subtotal of items not including S&H, or tax. - 'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'], 2), // Total shipping costs for the order. If you specify shippingamt, you must also specify itemamt. - 'handlingamt' => number_format($_SESSION['shopping_cart']['handling'], 2), // Total handling costs for the order. If you specify handlingamt, you must also specify itemamt. - 'taxamt' => number_format($_SESSION['shopping_cart']['tax'], 2), // Required if you specify itemized cart tax details. Sum of tax for all items on the order. Total sales tax. - 'desc' => 'Testing Payments Pro DESC Field', // Description of the order the customer is purchasing. 127 char max. - 'custom' => 'TEST', // Free-form field for your own use. 256 char max. - 'invnum' => 'ABC-123-XYZ', // Your own invoice or tracking number - 'buttonsource' => '', // An ID code for use by 3rd party apps to identify transactions. - 'notifyurl' => '' // URL for receiving Instant Payment Notifications. This overrides what your profile is set to use. -); - -/** - * Here we'll begin creating our order items that belong to this $Payment in the request. - * We will loop through the items in our shopping cart to add them each into our - * $Payment. - */ -$OrderItems = array(); -foreach ($_SESSION['shopping_cart']['acdc_items'] as $cart_item) { - $Item = array( - 'name' => $cart_item['name'], // Item name. 127 char max. - 'amt' => $cart_item['price'], // Cost of item. - 'number' => $cart_item['id'], // Item number. 127 char max. - 'qty' => $cart_item['qty'], // Item qty on order. Any positive integer. - ); - array_push($OrderItems, $Item); +$cart = $_SESSION['shopping_cart']; +$payer = $_SESSION['payer']; +$billing = $_SESSION['billing']; +$card_details = $_SESSION['card_details']; +$line_items = []; +foreach ($cart['acdc_items'] as $item) { + $line_items[] = [ + 'name' => $item['name'], + 'description' => $item['desc'], + 'sku' => $item['id'], + 'product_code' => $item['id'], + 'commodity_code' => '86101700', + 'unit_of_measure' => 'UNIT', + 'quantity' => (string)$item['qty'], + 'category' => $item['category'], + 'unit_amount' => [ + 'currency_code' => 'USD', + 'value' => number_format($item['price'], 2) + ], + 'unit_tax_amount' => [ + 'currency_code' => 'USD', + 'value' => number_format($item['tax'], 2) + ], + 'unit_discount_amount' => [ + 'currency_code' => 'USD', + 'value' => '0.00' + ] + ]; } -$PayPalRequestData = array( - 'DPFields' => $DPFields, - 'CCDetails' => $CCDetails, - 'PayerInfo' => $PayerInfo, - 'PayerName' => $PayerName, - 'BillingAddress' => $BillingAddress, - 'PaymentDetails' => $PaymentDetails, - 'OrderItems' => $OrderItems -); +$orderPayload = [ + "intent" => "CAPTURE", + "purchase_units" => [[ + "reference_id" => uniqid("ORDER-"), + "invoice_id" => uniqid("INV-"), + "amount" => [ + "currency_code" => "USD", + "value" => number_format($cart['grand_total'], 2), + "breakdown" => [ + "item_total" => [ + "currency_code" => "USD", + "value" => number_format($cart['subtotal'], 2) + ], + "shipping" => [ + "currency_code" => "USD", + "value" => number_format($cart['shipping'], 2) + ], + "handling" => [ + "currency_code" => "USD", + "value" => number_format($cart['handling'], 2) + ], + "tax_total" => [ + "currency_code" => "USD", + "value" => number_format($cart['tax'], 2) + ], + "discount" => [ + "currency_code" => "USD", + "value" => "0.00" + ], + "duty" => [ + "currency_code" => "USD", + "value" => "0.00" + ] + ] + ], + "items" => $line_items, + "shipping" => [ + "name" => [ + "full_name" => $payer['firstname'] . ' ' . $payer['lastname'] + ], + "address" => [ + "address_line_1" => $billing['street'], + "admin_area_2" => $billing['city'], + "admin_area_1" => $billing['state'], + "postal_code" => $billing['zip'], + "country_code" => $billing['countrycode'] + ] + ] + ]], + "payment_source" => [ + "card" => [ + "number" => $card_details['accountnumber'], + "expiry" => $card_details['expiry'], + "security_code" => $card_details['cvv'], + "name" => $payer['firstname'] . ' ' . $payer['lastname'], + "billing_address" => [ + "address_line_1" => $billing['street'], + "admin_area_2" => $billing['city'], + "admin_area_1" => $billing['state'], + "postal_code" => $billing['zip'], + "country_code" => $billing['countrycode'] + ], + "attributes" => [ + "verification" => [ + "method" => "SCA_ALWAYS" + ] + ], + "vault" => [ + "store_in_vault" => "ON_SUCCESS" + ], + "experience_context" => [ + "payment_method_preference" => "IMMEDIATE_PAYMENT_REQUIRED", + "user_action" => "PAY_NOW" + ] + ] + ] +]; -$PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData); +$paypalRequestId = uniqid('pprid_', true); + +$PayPalResult = $PayPal->createOrder($orderPayload, $paypalRequestId); /** * Now we'll check for any errors returned by PayPal, and if we get an error, @@ -121,17 +141,11 @@ * If the call is successful, we'll save some data we might want to use * later into session variables. */ -if( $api_mode === 'classic' && $PayPal->APICallSuccessful($PayPalResult['ACK']) ) { - $_SESSION['paypal_transaction_id'] = isset($PayPalResult['TRANSACTIONID']) ? $PayPalResult['TRANSACTIONID'] : ''; - header('Location: order-complete.php'); -} elseif( $api_mode === 'rest' && ($PayPalResult['SUCCESS'] || ( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' )) ) { +if( $PayPalResult['success'] ) { /** * Here we'll pull out data from the PayPal response. */ - $_SESSION['paypal_transaction_id'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['RESPONSE']['id']) ? $PayPalResult['RESPONSE']['id'] : '' ) - : ( isset($PayPalResult['TRANSACTIONID']) ? $PayPalResult['TRANSACTIONID'] : '' ); - + $_SESSION['paypal_transaction_id'] = isset($PayPalResult['full_response']['id']) ? $PayPalResult['full_response']['id'] : ''; $_SESSION['shipping_name'] = $_SESSION['payer']['firstname'] . ' ' . $_SESSION['payer']['lastname']; $_SESSION['shipping_street'] = $_SESSION['billing']['street']; $_SESSION['shipping_city'] = $_SESSION['billing']['city']; diff --git a/demo/paypal-checkout-advanced-credit-cards/acdc.js b/demo/paypal-checkout-advanced-credit-cards/acdc.js index db9c47aa..e2c62322 100644 --- a/demo/paypal-checkout-advanced-credit-cards/acdc.js +++ b/demo/paypal-checkout-advanced-credit-cards/acdc.js @@ -14,20 +14,20 @@ document.addEventListener("DOMContentLoaded", function () { const items = cart.acdc_items.map(item => ({ name: item.name, - description: "Item description", + description: item.desc, sku: item.id, product_code: item.id, commodity_code: "86101700", unit_of_measure: "UNIT", - quantity: item.qty, - category: "PHYSICAL_GOODS", + quantity: item.qty.toString(), + category: item.category, unit_amount: { currency_code: "USD", - value: item.price + value: Number(item.price).toFixed(2) }, unit_tax_amount: { currency_code: "USD", - value: "0.00" + value: Number(item.tax).toFixed(2) }, unit_discount_amount: { currency_code: "USD", @@ -43,23 +43,23 @@ document.addEventListener("DOMContentLoaded", function () { invoice_id: "INV-" + Date.now(), amount: { currency_code: "USD", - value: cart.grand_total, + value: Number(cart.grand_total).toFixed(2), breakdown: { item_total: { currency_code: "USD", - value: cart.subtotal, + value: Number(cart.subtotal).toFixed(2), }, shipping: { currency_code: "USD", - value: cart.shipping + value: Number(cart.shipping).toFixed(2), }, handling: { currency_code: "USD", - value: cart.handling + value: Number(cart.handling).toFixed(2), }, tax_total: { currency_code: "USD", - value: cart.tax + value: Number(cart.tax).toFixed(2), }, discount: { currency_code: "USD", diff --git a/demo/paypal-checkout-advanced-credit-cards/getOrder.php b/demo/paypal-checkout-advanced-credit-cards/getOrder.php index 37049df0..64e5200a 100644 --- a/demo/paypal-checkout-advanced-credit-cards/getOrder.php +++ b/demo/paypal-checkout-advanced-credit-cards/getOrder.php @@ -34,7 +34,6 @@ /** * Here we'll pull out data from the PayPal response. */ - $_SESSION['paypal_transaction_id'] = $_GET['order_id']; $_SESSION['paypal_payer_id'] = isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : ''; $_SESSION['phone_number'] = isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : ''; $_SESSION['email'] = isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : ''; @@ -42,6 +41,10 @@ $_SESSION['last_name'] = isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : ''; $_SESSION['billing_country_code'] = isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : ''; + $captures = !empty($PayPalResult['order']['purchase_units'][0]['payments']['captures'][0]) ? $PayPalResult['order']['purchase_units'][0]['payments']['captures'][0] : []; + $_SESSION['paypal_transaction_id'] = isset($captures['id']) ? $captures['id'] : ''; + $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; + $card = $PayPalResult['order']['payment_source']['card']; $_SESSION['card_name'] = $card['name']; $_SESSION['card_last4'] = $card['last_digits']; @@ -59,27 +62,6 @@ $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; $_SESSION['shipping_country_name'] = 'United States'; - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - */ - $_SESSION['shopping_cart']['shipping'] = 10.00; - $_SESSION['shopping_cart']['handling'] = 2.50; - $_SESSION['shopping_cart']['tax'] = 1.50; - - $_SESSION['shopping_cart']['grand_total'] = number_format( - $_SESSION['shopping_cart']['subtotal'] - + $_SESSION['shopping_cart']['shipping'] - + $_SESSION['shopping_cart']['handling'] - + $_SESSION['shopping_cart']['tax'],2); - /** * Now we will redirect the user to a final review * page so they can see the shipping/handling/tax diff --git a/demo/paypal-checkout-advanced-credit-cards/guest-checkout.js b/demo/paypal-checkout-advanced-credit-cards/guest-checkout.js index 26d3b3ad..df852481 100644 --- a/demo/paypal-checkout-advanced-credit-cards/guest-checkout.js +++ b/demo/paypal-checkout-advanced-credit-cards/guest-checkout.js @@ -12,20 +12,20 @@ document.addEventListener("DOMContentLoaded", function () { const items = cart.acdc_items.map(item => ({ name: item.name, - description: "Item description", + description: item.desc, sku: item.id, product_code: item.id, commodity_code: "86101700", unit_of_measure: "UNIT", - quantity: item.qty, - category: "PHYSICAL_GOODS", + quantity: item.qty.toString(), + category: item.category, unit_amount: { currency_code: "USD", - value: item.price + value: Number(item.price).toFixed(2) }, unit_tax_amount: { currency_code: "USD", - value: "0.00" + value: Number(item.tax).toFixed(2) }, unit_discount_amount: { currency_code: "USD", @@ -41,23 +41,23 @@ document.addEventListener("DOMContentLoaded", function () { invoice_id: "INV-" + Date.now(), amount: { currency_code: "USD", - value: cart.grand_total, + value: Number(cart.grand_total).toFixed(2), breakdown: { item_total: { currency_code: "USD", - value: cart.subtotal, + value: Number(cart.subtotal).toFixed(2), }, shipping: { currency_code: "USD", - value: cart.shipping + value: Number(cart.shipping).toFixed(2), }, handling: { currency_code: "USD", - value: cart.handling + value: Number(cart.handling).toFixed(2), }, tax_total: { currency_code: "USD", - value: cart.tax + value: Number(cart.tax).toFixed(2), }, discount: { currency_code: "USD", diff --git a/demo/paypal-checkout-advanced-credit-cards/index.php b/demo/paypal-checkout-advanced-credit-cards/index.php index de0d61c1..6e2c4251 100644 --- a/demo/paypal-checkout-advanced-credit-cards/index.php +++ b/demo/paypal-checkout-advanced-credit-cards/index.php @@ -28,7 +28,7 @@ $_SESSION['card_details'] = array( 'creditcardtype' => 'Visa', // Type of credit card. Visa, MasterCard, Discover, Amex, Maestro, Solo. If Maestro or Solo, the currency code must be GBP. In addition, either start date or issue number must be specified. 'accountnumber' => '4111111111111111', // Credit card number. No spaces or punctuation. - 'expiry' => '122026', // Credit card expiration date. Format is MMYYYY + 'expiry' => '2027-12', // Credit card expiration date. Format is MMYYYY 'cvv' => '456', // Requirements determined by your PayPal account settings. Security digits for credit card. ); @@ -62,15 +62,20 @@ $_SESSION['acdc_items'][0] = array( 'id' => '123-ABC', 'name' => 'Widget', + 'desc' => 'Widget 123', 'qty' => '2', 'price' => '9.99', + 'tax' => 0, + 'category' => 'PHYSICAL_GOODS', ); - $_SESSION['acdc_items'][1] = array( 'id' => 'XYZ-456', 'name' => 'Gadget', + 'desc' => 'Gadget 456', 'qty' => '1', 'price' => '4.99', + 'tax' => 0, + 'category' => 'PHYSICAL_GOODS', ); $_SESSION['shopping_cart'] = array( 'acdc_items' => $_SESSION['acdc_items'], @@ -211,15 +216,19 @@ -
- renderPayPalButton(); ?> - -
- - - + + + + + + -
OR
diff --git a/demo/paypal-checkout-advanced-credit-cards/order-complete.php b/demo/paypal-checkout-advanced-credit-cards/order-complete.php index 62e8a943..b6681a68 100644 --- a/demo/paypal-checkout-advanced-credit-cards/order-complete.php +++ b/demo/paypal-checkout-advanced-credit-cards/order-complete.php @@ -60,7 +60,7 @@

Payment Complete!

-

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID to the Billing Information, which was provided in the DoDirectPayment response.

+

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID to the Billing Information, which was provided in the response.

From 50ec7364eceae34e049c14b717ce1f99ecaac130 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Sat, 14 Mar 2026 19:59:37 +0530 Subject: [PATCH 136/146] Minor Changes in Direct Payment --- .../DoDirectPayment.php | 26 +++++++++++++------ .../order-complete.php | 2 +- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php b/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php index b9b78756..4a164b60 100644 --- a/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php +++ b/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php @@ -145,16 +145,26 @@ /** * Here we'll pull out data from the PayPal response. */ - $_SESSION['paypal_transaction_id'] = isset($PayPalResult['full_response']['id']) ? $PayPalResult['full_response']['id'] : ''; - $_SESSION['shipping_name'] = $_SESSION['payer']['firstname'] . ' ' . $_SESSION['payer']['lastname']; - $_SESSION['shipping_street'] = $_SESSION['billing']['street']; - $_SESSION['shipping_city'] = $_SESSION['billing']['city']; - $_SESSION['shipping_state'] = $_SESSION['billing']['state']; - $_SESSION['shipping_zip'] = $_SESSION['billing']['zip']; - $_SESSION['shipping_country_code'] = $_SESSION['billing']['countrycode']; + $orderID = isset($PayPalResult['full_response']['id']) ? $PayPalResult['full_response']['id'] : ''; + $getOrderResult = $PayPal->getOrder($orderID); + + if( $getOrderResult['success'] ) { + $_SESSION['paypal_order_id'] = isset($getOrderResult['order']['id']) ? $getOrderResult['order']['id'] : ''; + $purchaseUnit = $getOrderResult['order']['purchase_units'][0]; + $shipping = isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : []; + $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; + $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; + $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; + $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; + $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; + $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; + } else { + $_SESSION['paypal_errors'] = $getOrderResult['errors']; + header('Location: ../error.php'); + } header('Location: order-complete.php'); } else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; + $_SESSION['paypal_errors'] = $PayPalResult['errors']; header('Location: ../error.php'); } \ No newline at end of file diff --git a/demo/paypal-checkout-advanced-credit-cards/order-complete.php b/demo/paypal-checkout-advanced-credit-cards/order-complete.php index b6681a68..764e59a6 100644 --- a/demo/paypal-checkout-advanced-credit-cards/order-complete.php +++ b/demo/paypal-checkout-advanced-credit-cards/order-complete.php @@ -96,7 +96,7 @@ echo $_SESSION['payer']['firstname'] . ' ' . $_SESSION['payer']['lastname'] . '
' . $_SESSION['payer']['email'] . '
' . $_SESSION['payer']['phonenumber'] . '
' . - 'Transaction ID: ' . $_SESSION['paypal_transaction_id'] . '
+ 'PayPal OrderID: ' . $_SESSION['paypal_order_id'] . '
Payment Source: PayPal'; } elseif( isset($_SESSION['payment_mode']) && $_SESSION['payment_mode'] === 'guest' ) { echo $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '
' . From f9e381d1bc000b9bcb9937d0048ad7df2ac80cf8 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Sat, 14 Mar 2026 20:35:09 +0530 Subject: [PATCH 137/146] JS Improvemtns --- .../DoDirectPayment.php | 170 ----------------- .../acdc.js | 2 +- .../index.php | 6 +- .../order-complete.php | 8 +- .../paypal-payment.js | 174 ++++++++++++++++++ demo/paypal-checkout-basic/basic-paypal.js | 7 +- .../donation-order.js | 7 +- .../basic-paypal.js | 14 +- .../multiparty-payments.js | 7 +- .../shipping-cb.js | 7 +- 10 files changed, 214 insertions(+), 188 deletions(-) delete mode 100644 demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php create mode 100644 demo/paypal-checkout-advanced-credit-cards/paypal-payment.js diff --git a/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php b/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php deleted file mode 100644 index 4a164b60..00000000 --- a/demo/paypal-checkout-advanced-credit-cards/DoDirectPayment.php +++ /dev/null @@ -1,170 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'MerchantID' => $rest_merchant_id, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); - -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$cart = $_SESSION['shopping_cart']; -$payer = $_SESSION['payer']; -$billing = $_SESSION['billing']; -$card_details = $_SESSION['card_details']; -$line_items = []; -foreach ($cart['acdc_items'] as $item) { - $line_items[] = [ - 'name' => $item['name'], - 'description' => $item['desc'], - 'sku' => $item['id'], - 'product_code' => $item['id'], - 'commodity_code' => '86101700', - 'unit_of_measure' => 'UNIT', - 'quantity' => (string)$item['qty'], - 'category' => $item['category'], - 'unit_amount' => [ - 'currency_code' => 'USD', - 'value' => number_format($item['price'], 2) - ], - 'unit_tax_amount' => [ - 'currency_code' => 'USD', - 'value' => number_format($item['tax'], 2) - ], - 'unit_discount_amount' => [ - 'currency_code' => 'USD', - 'value' => '0.00' - ] - ]; -} - -$orderPayload = [ - "intent" => "CAPTURE", - "purchase_units" => [[ - "reference_id" => uniqid("ORDER-"), - "invoice_id" => uniqid("INV-"), - "amount" => [ - "currency_code" => "USD", - "value" => number_format($cart['grand_total'], 2), - "breakdown" => [ - "item_total" => [ - "currency_code" => "USD", - "value" => number_format($cart['subtotal'], 2) - ], - "shipping" => [ - "currency_code" => "USD", - "value" => number_format($cart['shipping'], 2) - ], - "handling" => [ - "currency_code" => "USD", - "value" => number_format($cart['handling'], 2) - ], - "tax_total" => [ - "currency_code" => "USD", - "value" => number_format($cart['tax'], 2) - ], - "discount" => [ - "currency_code" => "USD", - "value" => "0.00" - ], - "duty" => [ - "currency_code" => "USD", - "value" => "0.00" - ] - ] - ], - "items" => $line_items, - "shipping" => [ - "name" => [ - "full_name" => $payer['firstname'] . ' ' . $payer['lastname'] - ], - "address" => [ - "address_line_1" => $billing['street'], - "admin_area_2" => $billing['city'], - "admin_area_1" => $billing['state'], - "postal_code" => $billing['zip'], - "country_code" => $billing['countrycode'] - ] - ] - ]], - "payment_source" => [ - "card" => [ - "number" => $card_details['accountnumber'], - "expiry" => $card_details['expiry'], - "security_code" => $card_details['cvv'], - "name" => $payer['firstname'] . ' ' . $payer['lastname'], - "billing_address" => [ - "address_line_1" => $billing['street'], - "admin_area_2" => $billing['city'], - "admin_area_1" => $billing['state'], - "postal_code" => $billing['zip'], - "country_code" => $billing['countrycode'] - ], - "attributes" => [ - "verification" => [ - "method" => "SCA_ALWAYS" - ] - ], - "vault" => [ - "store_in_vault" => "ON_SUCCESS" - ], - "experience_context" => [ - "payment_method_preference" => "IMMEDIATE_PAYMENT_REQUIRED", - "user_action" => "PAY_NOW" - ] - ] - ] -]; - -$paypalRequestId = uniqid('pprid_', true); - -$PayPalResult = $PayPal->createOrder($orderPayload, $paypalRequestId); - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If the call is successful, we'll save some data we might want to use - * later into session variables. - */ -if( $PayPalResult['success'] ) { - /** - * Here we'll pull out data from the PayPal response. - */ - $orderID = isset($PayPalResult['full_response']['id']) ? $PayPalResult['full_response']['id'] : ''; - $getOrderResult = $PayPal->getOrder($orderID); - - if( $getOrderResult['success'] ) { - $_SESSION['paypal_order_id'] = isset($getOrderResult['order']['id']) ? $getOrderResult['order']['id'] : ''; - $purchaseUnit = $getOrderResult['order']['purchase_units'][0]; - $shipping = isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : []; - $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; - $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; - $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; - $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; - $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; - $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; - } else { - $_SESSION['paypal_errors'] = $getOrderResult['errors']; - header('Location: ../error.php'); - } - - header('Location: order-complete.php'); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['errors']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-checkout-advanced-credit-cards/acdc.js b/demo/paypal-checkout-advanced-credit-cards/acdc.js index e2c62322..c2a9aef6 100644 --- a/demo/paypal-checkout-advanced-credit-cards/acdc.js +++ b/demo/paypal-checkout-advanced-credit-cards/acdc.js @@ -241,7 +241,7 @@ document.addEventListener("DOMContentLoaded", function () { } } catch (err) { hideActions(); - console.error("Payment flow error", err); + showPaypalError(`Payment flow error: ${err}`) } } diff --git a/demo/paypal-checkout-advanced-credit-cards/index.php b/demo/paypal-checkout-advanced-credit-cards/index.php index 6e2c4251..6d0d8dfb 100644 --- a/demo/paypal-checkout-advanced-credit-cards/index.php +++ b/demo/paypal-checkout-advanced-credit-cards/index.php @@ -124,6 +124,7 @@ + @@ -222,7 +223,10 @@
- renderPayPalButton(); ?> +
'> +
+ +
diff --git a/demo/paypal-checkout-advanced-credit-cards/order-complete.php b/demo/paypal-checkout-advanced-credit-cards/order-complete.php index 764e59a6..978ba150 100644 --- a/demo/paypal-checkout-advanced-credit-cards/order-complete.php +++ b/demo/paypal-checkout-advanced-credit-cards/order-complete.php @@ -96,7 +96,13 @@ echo $_SESSION['payer']['firstname'] . ' ' . $_SESSION['payer']['lastname'] . '
' . $_SESSION['payer']['email'] . '
' . $_SESSION['payer']['phonenumber'] . '
' . - 'PayPal OrderID: ' . $_SESSION['paypal_order_id'] . '
+ 'Transaction ID: ' . $_SESSION['paypal_transaction_id'] . '
+ Payment Source: PayPal'; + } elseif( isset($_SESSION['payment_mode']) && $_SESSION['payment_mode'] === 'paypal' ) { + echo $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '
' . + $_SESSION['email'] . '
'. + $_SESSION['phone_number'] . '
' . + 'Transaction ID: ' . $_SESSION['paypal_transaction_id'] . '
Payment Source: PayPal'; } elseif( isset($_SESSION['payment_mode']) && $_SESSION['payment_mode'] === 'guest' ) { echo $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '
' . diff --git a/demo/paypal-checkout-advanced-credit-cards/paypal-payment.js b/demo/paypal-checkout-advanced-credit-cards/paypal-payment.js new file mode 100644 index 00000000..509b49a8 --- /dev/null +++ b/demo/paypal-checkout-advanced-credit-cards/paypal-payment.js @@ -0,0 +1,174 @@ +document.addEventListener("DOMContentLoaded", function () { + const payPalBtnContainer = document.getElementById("paypal-button-container"); + if ( !payPalBtnContainer ) return; + + const checkoutData = JSON.parse(payPalBtnContainer.dataset.checkout); + + async function createOrder() { + try { + const items = checkoutData.acdc_items.map(item => ({ + name: item.name, + description: item.desc, + sku: item.id, + quantity: item.qty.toString(), + category: item.category, + unit_amount: { + currency_code: "USD", + value: Number(item.price).toFixed(2) + } + })); + + const orderPayload = { + intent: "CAPTURE", + purchase_units: [ + { + amount: { + currency_code: "USD", + value: Number(checkoutData.grand_total).toFixed(2), + breakdown: { + item_total: { + currency_code: "USD", + value: Number(checkoutData.subtotal).toFixed(2), + }, + shipping: { + currency_code: "USD", + value: Number(checkoutData.shipping).toFixed(2), + }, + handling: { + currency_code: "USD", + value: Number(checkoutData.handling).toFixed(2), + }, + tax_total: { + currency_code: "USD", + value: Number(checkoutData.tax).toFixed(2), + }, + }, + }, + items: items, + }, + ], + payment_source: { + paypal: { + experience_context: { + brand_name: "AngellEYE", + shipping_preference: "GET_FROM_FILE", + user_action: "PAY_NOW" + } + } + } + }; + + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(orderPayload) + }) + + const data = await response.json(); + if (!data.order_id) { + showPaypalError("Unable to create PayPal order."); + return; + } + + return { orderId: data?.order_id }; + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + function showPaypalError(message) { + const errorContainer = document.getElementById('paypalError'); + if( !errorContainer ) return; + errorContainer.style.display = "block"; + errorContainer.innerHTML = message; + } + + async function captureOrder(data) { + try { + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_capture_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id: data.orderId }), + }); + + const captureResult = await response.json(); + + if (captureResult.status === "COMPLETED") { + window.location.href = `getOrder.php?payment_mode=paypal&order_id=${data.orderId}`; + } else { + throw new Error("Payment capture failed."); + } + + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + const paymentSessionOptions = { + async onApprove(data) { + try { + const orderData = await captureOrder({ + orderId: data.orderId, + }); + } catch (error) { + showPaypalError(error.message); + throw error; + } + }, + onCancel() { + location.reload(); + }, + onError(error) { + showPaypalError(error.message); + }, + }; + + async function init() { + try { + const res = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_client_token'); + const { token } = await res.json(); + + const sdkInstance = await window.paypal.createInstance({ + clientToken: token, + components: ['paypal-payments'], + pageType: 'checkout' + }); + + const paymentMethods = await sdkInstance.findEligibleMethods({ + currencyCode: "USD", + }); + + if (paymentMethods.isEligible("paypal")) { + setUpPayPalButton(sdkInstance); + } + } catch (error) { + showPaypalError(`Initialization error: ${error.message}`); + throw error; + } + } + + // Set up standard PayPal button + async function setUpPayPalButton(sdkInstance) { + const paypalPaymentSession = sdkInstance.createPayPalOneTimePaymentSession( + paymentSessionOptions, + ); + + const paypalButton = document.querySelector("paypal-button"); + paypalButton.removeAttribute("hidden"); + + paypalButton.addEventListener("click", async () => { + try { + await paypalPaymentSession.start( + { presentationMode: "auto" }, + createOrder(), + ); + } catch (error) { + showPaypalError(`PayPal payment start error: ${error}`) + } + }); + } + + init(); +}); \ No newline at end of file diff --git a/demo/paypal-checkout-basic/basic-paypal.js b/demo/paypal-checkout-basic/basic-paypal.js index 681091c3..a5af2c11 100644 --- a/demo/paypal-checkout-basic/basic-paypal.js +++ b/demo/paypal-checkout-basic/basic-paypal.js @@ -35,7 +35,7 @@ document.addEventListener("DOMContentLoaded", function () { const data = await response.json(); if (!data.order_id) { - console.log(data.message || "Unable to create PayPal order."); + showPaypalError("Unable to create PayPal order."); return; } @@ -47,8 +47,9 @@ document.addEventListener("DOMContentLoaded", function () { } function showPaypalError(message) { - const errorContainer = payPalBtnContainer.getElementById('paypalError'); + const errorContainer = document.getElementById('paypalError'); if( !errorContainer ) return; + errorContainer.style.display = "block"; errorContainer.innerHTML = message; } @@ -133,7 +134,7 @@ document.addEventListener("DOMContentLoaded", function () { createOrder(), ); } catch (error) { - console.error("PayPal payment start error:", error); + showPaypalError(`PayPal payment start error: ${error}`) } }); } diff --git a/demo/paypal-checkout-donation/donation-order.js b/demo/paypal-checkout-donation/donation-order.js index ff3f8cf2..33a3e775 100644 --- a/demo/paypal-checkout-donation/donation-order.js +++ b/demo/paypal-checkout-donation/donation-order.js @@ -59,7 +59,7 @@ document.addEventListener("DOMContentLoaded", function () { const data = await response.json(); if (!data.order_id) { - console.log(data.message || "Unable to create PayPal order."); + showPaypalError("Unable to create PayPal order."); return; } @@ -71,8 +71,9 @@ document.addEventListener("DOMContentLoaded", function () { } function showPaypalError(message) { - const errorContainer = payPalBtnContainer.getElementById('paypalError'); + const errorContainer = document.getElementById('paypalError'); if( !errorContainer ) return; + errorContainer.style.display = "block"; errorContainer.innerHTML = message; } @@ -157,7 +158,7 @@ document.addEventListener("DOMContentLoaded", function () { createOrder(), ); } catch (error) { - console.error("PayPal payment start error:", error); + showPaypalError(`PayPal payment start error: ${error}`) } }); } diff --git a/demo/paypal-checkout-line-items/basic-paypal.js b/demo/paypal-checkout-line-items/basic-paypal.js index f40e8d28..fcaad7ef 100644 --- a/demo/paypal-checkout-line-items/basic-paypal.js +++ b/demo/paypal-checkout-line-items/basic-paypal.js @@ -24,7 +24,14 @@ document.addEventListener("DOMContentLoaded", function () { amount: { currency_code: "USD", value: Number(checkoutData.grand_total).toFixed(2), + breakdown: { + item_total: { + currency_code: "USD", + value: Number(checkoutData.subtotal).toFixed(2), + }, + }, }, + items: items, }, ], payment_source: { @@ -46,7 +53,7 @@ document.addEventListener("DOMContentLoaded", function () { const data = await response.json(); if (!data.order_id) { - console.log(data.message || "Unable to create PayPal order."); + showPaypalError("Unable to create PayPal order."); return; } @@ -58,8 +65,9 @@ document.addEventListener("DOMContentLoaded", function () { } function showPaypalError(message) { - const errorContainer = payPalBtnContainer.getElementById('paypalError'); + const errorContainer = document.getElementById('paypalError'); if( !errorContainer ) return; + errorContainer.style.display = "block"; errorContainer.innerHTML = message; } @@ -144,7 +152,7 @@ document.addEventListener("DOMContentLoaded", function () { createOrder(), ); } catch (error) { - console.error("PayPal payment start error:", error); + showPaypalError(`PayPal payment start error: ${error}`) } }); } diff --git a/demo/paypal-checkout-multiparty/multiparty-payments.js b/demo/paypal-checkout-multiparty/multiparty-payments.js index 3ab5200b..8328884f 100644 --- a/demo/paypal-checkout-multiparty/multiparty-payments.js +++ b/demo/paypal-checkout-multiparty/multiparty-payments.js @@ -75,7 +75,7 @@ document.addEventListener("DOMContentLoaded", function () { const data = await response.json(); if (!data.order_id) { - console.log(data.message || "Unable to create PayPal order."); + showPaypalError("Unable to create PayPal order."); return; } @@ -87,8 +87,9 @@ document.addEventListener("DOMContentLoaded", function () { } function showPaypalError(message) { - const errorContainer = payPalBtnContainer.getElementById('paypalError'); + const errorContainer = document.getElementById('paypalError'); if( !errorContainer ) return; + errorContainer.style.display = "block"; errorContainer.innerHTML = message; } @@ -173,7 +174,7 @@ document.addEventListener("DOMContentLoaded", function () { createOrder(), ); } catch (error) { - console.error("PayPal payment start error:", error); + showPaypalError(`PayPal payment start error: ${error}`) } }); } diff --git a/demo/paypal-checkout-shipping-callback/shipping-cb.js b/demo/paypal-checkout-shipping-callback/shipping-cb.js index 86462c26..37504fd7 100644 --- a/demo/paypal-checkout-shipping-callback/shipping-cb.js +++ b/demo/paypal-checkout-shipping-callback/shipping-cb.js @@ -68,7 +68,7 @@ document.addEventListener("DOMContentLoaded", function () { const data = await response.json(); if (!data.order_id) { - console.log(data.message || "Unable to create PayPal order."); + showPaypalError("Unable to create PayPal order."); return; } @@ -80,8 +80,9 @@ document.addEventListener("DOMContentLoaded", function () { } function showPaypalError(message) { - const errorContainer = payPalBtnContainer.getElementById('paypalError'); + const errorContainer = document.getElementById('paypalError'); if( !errorContainer ) return; + errorContainer.style.display = "block"; errorContainer.innerHTML = message; } @@ -166,7 +167,7 @@ document.addEventListener("DOMContentLoaded", function () { createOrder(), ); } catch (error) { - console.error("PayPal payment start error:", error); + showPaypalError(`PayPal payment start error: ${error}`) } }); } From 3c6c6f8d94f478f7c447a1c6aded1537e8db999f Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 12:02:42 +0530 Subject: [PATCH 138/146] Changes for the Subscription Items --- .../CreateRecurringPaymentsProfile.php | 122 ++--------- .../GetExpressCheckoutDetails.php | 207 ------------------ .../GetRecurringPaymentsProfileDetails.php | 15 +- .../SetExpressCheckout.php | 136 ------------ .../getOrder.php | 97 ++++++++ .../index.php | 33 ++- .../order-complete.php | 8 +- .../review.php | 5 + .../subscription-shippped.js | 143 ++++++++++++ 9 files changed, 288 insertions(+), 478 deletions(-) delete mode 100644 demo/paypal-checkout-subscriptions-shipped/GetExpressCheckoutDetails.php delete mode 100644 demo/paypal-checkout-subscriptions-shipped/SetExpressCheckout.php create mode 100644 demo/paypal-checkout-subscriptions-shipped/getOrder.php create mode 100644 demo/paypal-checkout-subscriptions-shipped/subscription-shippped.js diff --git a/demo/paypal-checkout-subscriptions-shipped/CreateRecurringPaymentsProfile.php b/demo/paypal-checkout-subscriptions-shipped/CreateRecurringPaymentsProfile.php index 870e3ff9..28437bfc 100644 --- a/demo/paypal-checkout-subscriptions-shipped/CreateRecurringPaymentsProfile.php +++ b/demo/paypal-checkout-subscriptions-shipped/CreateRecurringPaymentsProfile.php @@ -5,6 +5,11 @@ require_once('../../includes/config.php'); require_once('../../vendor/autoload.php'); +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} + /** * Setup configuration for the PayPal library using vars from the config file. * Then load the PayPal object into $PayPal @@ -13,9 +18,6 @@ 'Sandbox' => $sandbox, 'PayPalAPIMode' => $api_mode, 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, 'ClientID' => $rest_client_id, 'ClientSecret' => $rest_client_secret, 'PrintHeaders' => $print_headers, @@ -24,86 +26,6 @@ ); $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); -/** - * Token returned from PayPal SetExpressCheckout. - */ -$CRPPFields = array( - 'token' => isset($_SESSION['paypal_token']) ? $_SESSION['paypal_token'] : '', -); - -/** - * Here we are setting up the parameters for a basic Express Checkout flow. - * - * The template provided at ../../vendor/angelleye/paypal-php-library/samples/classic/CreateRecurringPaymentsProfile.php - * contains a lot more parameters that we aren't using here, so I've removed them to keep this clean. - * - * $domain used here is set in the config file. - */ -$DaysTimestamp = strtotime('now'); -$Mo = date('m', $DaysTimestamp); -$Day = date('d', $DaysTimestamp); -$Year = date('Y', $DaysTimestamp); -$StartDateGMT = $Year . '-' . $Mo . '-' . $Day . 'T00:00:00\Z'; - -$firstname = isset($_SESSION['first_name']) ? $_SESSION['first_name'] : ''; -$lastname = isset($_SESSION['last_name']) ? $_SESSION['last_name'] : ''; - -/** - * Subscriber Details - */ -$ProfileDetails = array( - 'subscribername' => $firstname.' '.$lastname, // Full name of the person receiving the product or service paid for by the recurring payment. 32 char max. - 'profilestartdate' => $StartDateGMT, // Required. The date when the billing for this profile begins. Must be a valid date in UTC/GMT format. - 'profilereference' => '' // The merchant's own unique invoice number or reference ID. 127 char max. -); - -/** - * Subscriber's Schedule Details - */ -$ScheduleDetails = array( - 'desc' => $_SESSION['subscription']['name'], // Required. Description of the recurring payment. This field must match the corresponding billing agreement description included in SetExpressCheckout. - 'maxfailedpayments' => '3', // The number of scheduled payment periods that can fail before the profile is automatically suspended. - 'autobillamt' => 'AddToNextBilling' // This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle. Values can be: NoAutoBill or AddToNextBilling -); - -$BillingPeriod = array( - 'trialbillingperiod' => '', - 'trialbillingfrequency' => '', - 'trialtotalbillingcycles' => '', - 'trialamt' => '', - 'billingperiod' => $_SESSION['subscription']['billing_period'], // Required. Unit for billing during this subscription period. One of the following: Day, Week, SemiMonth, Month, Year - 'billingfrequency' => $_SESSION['subscription']['billing_frequency'], // Required. Number of billing periods that make up one billing cycle. The combination of billing freq. and billing period must be less than or equal to one year. - 'totalbillingcycles' => $_SESSION['subscription']['total_billing_cycles'], // the number of billing cycles for the payment period (regular or trial). For trial period it must be greater than 0. For regular payments 0 means indefinite...until canceled. - 'amt' => $_SESSION['subscription']['amount'], // Required. Billing amount for each billing cycle during the payment period. This does not include shipping and tax. - 'currencycode' => 'USD', // Required. Three-letter currency code. - 'shippingamt' => $_SESSION['shopping_cart']['shipping'], // Shipping amount for each billing cycle during the payment period. - 'taxamt' => $_SESSION['shopping_cart']['tax'] // Tax amount for each billing cycle during the payment period. -); - -$ActivationDetails = array( - 'initamt' => $_SESSION['shopping_cart']['grand_total'], // Initial non-recurring payment amount due immediatly upon profile creation. Use an initial amount for enrolment or set-up fees. - 'failedinitamtaction' => '', // By default, PayPal will suspend the pending profile in the event that the initial payment fails. You can override this. Values are: ContinueOnFailure or CancelOnFailure -); - -/** - * Payer details - */ -$PayerInfo = array( - 'email' => isset($_SESSION['email']) ? $_SESSION['email'] : '', // Email address of payer. - 'payerid' => isset($_SESSION['paypal_payer_id']) ? $_SESSION['paypal_payer_id'] : '', // Unique PayPal customer ID for payer. - 'payerstatus' => '', // Status of payer. Values are verified or unverified - 'countrycode' => '', // Payer's country of residence in the form of the two letter code. - 'business' => '' // Payer's business name. -); - -$PayerName = array( - 'salutation' => '', // Payer's salutation. 20 char max. - 'firstname' => $firstname, // Payer's first name. 25 char max. - 'middlename' => '', // Payer's middle name. 25 char max. - 'lastname' => $lastname, // Payer's last name. 25 char max. - 'suffix' => '' // Payer's suffix. 12 char max. -); - $ProductData = array( "name" => $_SESSION['subscription']['name'], "description" => $_SESSION['subscription']['name'], @@ -163,39 +85,25 @@ * Now we gather all of the arrays above into a single array. */ $PayPalRequestData = array( - 'ProfileDetails' => $ProfileDetails, - 'ScheduleDetails' => $ScheduleDetails, - 'BillingPeriod' => $BillingPeriod, - 'PayerInfo' => $PayerInfo, - 'PayerName' => $PayerName, - 'CRPPFields' => $CRPPFields, - 'ActivationDetails' => $ActivationDetails, 'ProductData' => $ProductData, 'PlanData' => $PlanData, 'SubscriptionData' => $SubscriptionData, ); -if ( $api_mode === 'classic' ) { - $PayPalResult = $PayPal->CreateRecurringPaymentsProfile($PayPalRequestData); - - $_SESSION['RecurringProfileId'] = $PayPalResult['PROFILEID']; - header('Location: order-complete.php'); -} elseif( $api_mode == 'rest' ) { - $PayPalResult = $PayPal->CreateSubscriptionProfile($PayPalRequestData); +$PayPalResult = $PayPal->CreateSubscriptionProfile($PayPalRequestData); - if ($PayPalResult['success']) { - $approve_url = ''; - if (!empty($PayPalResult['response']['links'])) { - foreach ($PayPalResult['response']['links'] as $link) { - if (isset($link['rel']) && $link['rel'] === 'approve') { - $approve_url = $link['href']; - break; - } +if ($PayPalResult['success']) { + $approve_url = ''; + if (!empty($PayPalResult['response']['links'])) { + foreach ($PayPalResult['response']['links'] as $link) { + if (isset($link['rel']) && $link['rel'] === 'approve') { + $approve_url = $link['href']; + break; } } - - header('Location: ' . $approve_url); } + + header('Location: ' . $approve_url); } else { $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; header('Location: ../error.php'); diff --git a/demo/paypal-checkout-subscriptions-shipped/GetExpressCheckoutDetails.php b/demo/paypal-checkout-subscriptions-shipped/GetExpressCheckoutDetails.php deleted file mode 100644 index e66ad945..00000000 --- a/demo/paypal-checkout-subscriptions-shipped/GetExpressCheckoutDetails.php +++ /dev/null @@ -1,207 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$DECPFields = array( - 'token' => $_SESSION['paypal_token'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. - 'payerid' => '', // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. -); - -/** - * Now we begin setting up our payment(s). - * - * Express Checkout includes the ability to setup parallel payments, - * so we have to populate our $Payments array here accordingly. - * - * For this sample (and in most use cases) we only need a single payment, - * but we still have to populate $Payments with a single $Payment array. - * - * Once again, the template file includes a lot more available parameters, - * but for this basic sample we've removed everything that we're not using, - * so all we have is an amount. - */ -$Payments = array(); -$Payment = array( - 'amt' => $_SESSION['shopping_cart']['grand_total'], // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. -); - -/** - * Here we push our single $Payment into our $Payments array. - */ -array_push($Payments, $Payment); - -/** - * Now we gather all of the arrays above into a single array. - */ -$PayPalRequestData = array( - 'DECPFields' => $DECPFields, - 'Payments' => $Payments, -); - -/* - * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal - */ -if ( $api_mode === 'rest' ) { - $PayPalResult = $PayPal->GetExpressCheckoutDetails($PayPalRequestData); -} else { - $PayPalResult = $PayPal->GetExpressCheckoutDetails($_SESSION['paypal_token']); -} - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If the call is successful, we'll save some data we might want to use - * later into session variables. - */ -if( $api_mode === 'classic' && $PayPal->APICallSuccessful($PayPalResult['ACK']) ) { - /** - * Here we'll pull out data from the PayPal response. - * Refer to the PayPal API Reference for all of the variables available - * in $PayPalResult['variablename'] - * - * https://developer.paypal.com/docs/classic/api/merchant/GetExpressCheckoutDetails_API_Operation_NVP/ - * - * Again, Express Checkout allows for parallel payments, so what we're doing here - * is usually the library to parse out the individual payments using the GetPayments() - * method so that we can easily access the data. - * - * We only have a single payment here, which will be the case with most checkouts, - * but we will still loop through the $Payments array returned by the library - * to grab our data accordingly. - */ - $_SESSION['paypal_payer_id'] = isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : ''; - $_SESSION['phone_number'] = isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : ''; - $_SESSION['email'] = isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : ''; - $_SESSION['first_name'] = isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : ''; - $_SESSION['last_name'] = isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : ''; - - $payments = $PayPal->GetPayments($PayPalResult); - - foreach($payments as $payment) - { - $_SESSION['shipping_name'] = isset($payment['SHIPTONAME']) ? $payment['SHIPTONAME'] : ''; - $_SESSION['shipping_street'] = isset($payment['SHIPTOSTREET']) ? $payment['SHIPTOSTREET'] : ''; - $_SESSION['shipping_city'] = isset($payment['SHIPTOCITY']) ? $payment['SHIPTOCITY'] : ''; - $_SESSION['shipping_state'] = isset($payment['SHIPTOSTATE']) ? $payment['SHIPTOSTATE'] : ''; - $_SESSION['shipping_zip'] = isset($payment['SHIPTOZIP']) ? $payment['SHIPTOZIP'] : ''; - $_SESSION['shipping_country_code'] = isset($payment['SHIPTOCOUNTRYCODE']) ? $payment['SHIPTOCOUNTRYCODE'] : ''; - $_SESSION['shipping_country_name'] = isset($payment['SHIPTOCOUNTRYNAME']) ? $payment['SHIPTOCOUNTRYNAME'] : ''; - } - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - */ - $_SESSION['shopping_cart']['shipping'] = 10.00; - $_SESSION['shopping_cart']['handling'] = 2.50; - $_SESSION['shopping_cart']['tax'] = 1.50; - - $_SESSION['shopping_cart']['grand_total'] = number_format( - $_SESSION['shopping_cart']['subtotal'] - + $_SESSION['shopping_cart']['shipping'] - + $_SESSION['shopping_cart']['handling'] - + $_SESSION['shopping_cart']['tax'],2); - - /** - * Now we will redirect the user to a final review - * page so they can see the shipping/handling/tax - * that has been added to the order. - */ - header('Location: review.php'); -} elseif( $api_mode === 'rest' && ($PayPalResult['success'] || ( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' )) ) { - /** - * Here we'll pull out data from the PayPal response. - */ - $_SESSION['paypal_payer_id'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : '' ) - : ( isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : '' ); - $_SESSION['phone_number'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : '' ) - : ( isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : '' ); - $_SESSION['email'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : '' ) - : ( isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : '' ); - $_SESSION['first_name'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['name']['given_name']) ? $PayPalResult['order']['payer']['name']['given_name'] : '' ) - : ( isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : '' ); - $_SESSION['last_name'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : '' ) - : ( isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : '' ); - $_SESSION['billing_country_code'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : '' ) - : ( isset($PayPalResult['COUNTRYCODE']) ? $PayPalResult['COUNTRYCODE'] : '' ); - - $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; - $shipping = ( ! $api_upgrade ) - ? ( isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : [] ) - : ( isset( $PayPalResult['SHIPPINGDATA'] ) ? $PayPalResult['SHIPPINGDATA'] : [] ); - $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; - $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; - $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; - $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; - $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; - $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; - $_SESSION['shipping_country_name'] = 'United States'; - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - */ - $_SESSION['shopping_cart']['shipping'] = 10.00; - $_SESSION['shopping_cart']['handling'] = 2.50; - $_SESSION['shopping_cart']['tax'] = 1.50; - - $_SESSION['shopping_cart']['grand_total'] = number_format( - $_SESSION['shopping_cart']['subtotal'] - + $_SESSION['shopping_cart']['shipping'] - + $_SESSION['shopping_cart']['handling'] - + $_SESSION['shopping_cart']['tax'],2); - - /** - * Now we will redirect the user to a final review - * page so they can see the shipping/handling/tax - * that has been added to the order. - */ - header('Location: review.php'); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-checkout-subscriptions-shipped/GetRecurringPaymentsProfileDetails.php b/demo/paypal-checkout-subscriptions-shipped/GetRecurringPaymentsProfileDetails.php index 7961d8ef..9b89826d 100644 --- a/demo/paypal-checkout-subscriptions-shipped/GetRecurringPaymentsProfileDetails.php +++ b/demo/paypal-checkout-subscriptions-shipped/GetRecurringPaymentsProfileDetails.php @@ -3,6 +3,11 @@ require_once('../../includes/config.php'); require_once('../../autoload.php'); +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} + // Create PayPal object. $PayPalConfig = array( 'Sandbox' => $sandbox, @@ -19,19 +24,15 @@ // Prepare request arrays $PayPalRequestData = array( - 'token' => isset($_GET['token']) ? $_GET['token'] : '', - 'ba_token' => isset($_GET['ba_token']) ? $_GET['ba_token'] : '', - 'subscription_id' => isset($_GET['subscription_id']) ? $_GET['subscription_id'] : '', + 'subscription_id' => isset($_GET['subscription_id']) ? $_GET['subscription_id'] : '', ); // Pass data into class for processing with PayPal and load the response array into $PayPalResult $PayPalResult = $PayPal->GetSubscriptionProfile($PayPalRequestData); -if( $PayPalResult['success'] || ( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' ) ) { +if( $PayPalResult['success'] ) { $full_response = ( !$api_upgrade && isset( $PayPalResult['full_response'] ) ) ? $PayPalResult['full_response'] : []; - $_SESSION['RecurringProfileId'] = ( ! $api_upgrade ) - ? ( ( !empty( $full_response ) && isset( $full_response['id'] ) ) ? $full_response['id'] : '' ) - : ( isset( $PayPalResult['PROFILEID'] ) ? $PayPalResult['PROFILEID'] : '' ); + $_SESSION['RecurringProfileId'] = ( !empty( $full_response ) && isset( $full_response['id'] ) ) ? $full_response['id'] : ''; header('Location: order-complete.php'); } else { diff --git a/demo/paypal-checkout-subscriptions-shipped/SetExpressCheckout.php b/demo/paypal-checkout-subscriptions-shipped/SetExpressCheckout.php deleted file mode 100644 index 5d137964..00000000 --- a/demo/paypal-checkout-subscriptions-shipped/SetExpressCheckout.php +++ /dev/null @@ -1,136 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -/** - * Here we are setting up the parameters for a basic Express Checkout flow. - * - * The template provided at ../../vendor/angelleye/paypal-php-library/templates/SetExpressCheckout.php - * contains a lot more parameters that we aren't using here, so I've removed them to keep this clean. - * - * We are including the Billing Agreement paramters here so that the token we get back from PayPal - * will be valid for both DoExpressCheckoutPayment and CreateRecurringPaymentsProfile later. - * - * $domain used here is set in the config file. - */ -$SECFields = array( - 'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), // The expected maximum total amount the order will be, including S&H and sales tax. - 'returnurl' => $domain . 'demo/paypal-checkout-subscriptions-shipped/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. - 'cancelurl' => $domain . 'demo/paypal-checkout-subscriptions-shipped/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. - 'L_BILLINGTYPE0' => 'RecurringPayments', - 'L_BILLINGAGREEMENTDESCRIPTION0' => $_SESSION['shopping_cart']['subscription']['name'], - 'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. - 'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', // A URL to your logo image. Formats: .gif, .jpg, .png. 190x60. PayPal places your logo image at the top of the cart review area. This logo needs to be stored on a https:// server. - 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. - 'customerservicenumber' => '816-555-5555', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. -); - -// Buyer email fetched from session -$PayerData = array( - 'buyeremail' => $_SESSION['buyer_email'] // buyer email address -); - -/** - * Now we begin setting up our payment(s). - * - * Express Checkout includes the ability to setup parallel payments, - * so we have to populate our $Payments array here accordingly. - * - * For this sample (and in most use cases) we only need a single payment, - * but we still have to populate $Payments with a single $Payment array. - * - * Once again, the template file includes a lot more available parameters, - * but for this basic sample we've removed everything that we're not using, - * so all we have is an amount. - */ -$Payments = array(); -$Payment = array( - 'amt' => $_SESSION['shopping_cart']['grand_total'], // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. -); - -/** - * Here we push our single $Payment into our $Payments array if api_mode is rest. - */ -if( $api_mode === 'rest' ) { - array_push($Payments, $Payment); -} - -/** - * Now we gather all of the arrays above into a single array. - */ -$PayPalRequestData = array( - 'SECFields' => $SECFields, - 'Payments' => $Payments, - 'PayerData' => $PayerData, -); - -/** - * Here we are making the call to the SetExpressCheckout function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ -$PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData); - -/** - * Based on the selected API mode, extract the appropriate redirect URL - * and order identifier from the SetExpressCheckout response. - * - * - For REST mode (when API upgrade is disabled), PayPal returns an - * `approval_url` for redirection and an `order_id` to track the transaction. - * - For Classic mode (or when API upgrade is enabled), PayPal returns a - * `REDIRECTURL` for redirection and a `TOKEN` that represents the checkout session. - * - * These values are normalized into $redirect_url and $orderId so the - * remaining flow can work consistently regardless of API mode. - */ -$redirect_url = ''; -if( $api_mode === 'rest' && !$api_upgrade ) { - $redirect_url = $PayPalResult['approval_url']; -} else { - $redirect_url = $PayPalResult['REDIRECTURL']; -} - -$orderId = ''; -if( $api_mode === 'rest' && !$api_upgrade ) { - $orderId = $PayPalResult['order_id']; -} else { - $orderId = $PayPalResult['TOKEN']; -} - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If all goes well, we save our token in a session variable so that it's - * readily available for us later, and then redirect the user to PayPal - * using the REDIRECTURL returned by the SetExpressCheckout() function. - */ -if($redirect_url) { - $_SESSION['paypal_token'] = $orderId; - header('Location: ' . $redirect_url); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-checkout-subscriptions-shipped/getOrder.php b/demo/paypal-checkout-subscriptions-shipped/getOrder.php new file mode 100644 index 00000000..e9922cdd --- /dev/null +++ b/demo/paypal-checkout-subscriptions-shipped/getOrder.php @@ -0,0 +1,97 @@ + $sandbox, + 'PayPalAPIMode' => $api_mode, + 'PayPalAPIUpgrade' => $api_upgrade, + 'ClientID' => $rest_client_id, + 'ClientSecret' => $rest_client_secret, + 'PrintHeaders' => $print_headers, + 'LogResults' => $log_results, + 'LogPath' => $log_path, +); +$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); + +/* + * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal + */ +$PayPalResult = $PayPal->getOrder($_GET['order_id']); + +/** + * Now we'll check for any errors returned by PayPal, and if we get an error, + * we'll save the error details to a session and redirect the user to an + * error page to display it accordingly. + * + * If the call is successful, we'll save some data we might want to use + * later into session variables. + */ +if( $PayPalResult['success'] ) { + /** + * Here we'll pull out data from the PayPal response. + */ + $_SESSION['paypal_payer_id'] = isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : ''; + $_SESSION['phone_number'] = isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : ''; + $_SESSION['email'] = isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : ''; + $_SESSION['first_name'] = isset($PayPalResult['order']['payer']['name']['given_name']) ? $PayPalResult['order']['payer']['name']['given_name'] : ''; + $_SESSION['last_name'] = isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : ''; + $_SESSION['billing_country_code'] = isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : ''; + + $captures = !empty($PayPalResult['order']['purchase_units'][0]['payments']['captures'][0]) ? $PayPalResult['order']['purchase_units'][0]['payments']['captures'][0] : []; + $_SESSION['paypal_transaction_id'] = isset($captures['id']) ? $captures['id'] : ''; + $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; + + $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; + $shipping = isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : []; + $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; + $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; + $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; + $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; + $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; + $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; + $_SESSION['shipping_country_name'] = 'United States'; + + /** + * At this point, we now have the buyer's shipping address available in our app. + * We could now run the data through a shipping calculator to retrieve rate + * information for this particular order. + * + * This would also be the time to calculate any sales tax you may need to + * add to the order, as well as handling fees. + * + * We're going to set static values for these things in our static + * shopping cart, and then re-calculate our grand total. + */ + $_SESSION['shopping_cart']['shipping'] = 10.00; + $_SESSION['shopping_cart']['handling'] = 2.50; + $_SESSION['shopping_cart']['tax'] = 1.50; + + $_SESSION['shopping_cart']['grand_total'] = number_format( + $_SESSION['shopping_cart']['subtotal'] + + $_SESSION['shopping_cart']['shipping'] + + $_SESSION['shopping_cart']['handling'] + + $_SESSION['shopping_cart']['tax'],2); + + /** + * Now we will redirect the user to a final review + * page so they can see the shipping/handling/tax + * that has been added to the order. + */ + header('Location: review.php'); +} else { + $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; + header('Location: ../error.php'); +} \ No newline at end of file diff --git a/demo/paypal-checkout-subscriptions-shipped/index.php b/demo/paypal-checkout-subscriptions-shipped/index.php index 6a91e585..798f1783 100644 --- a/demo/paypal-checkout-subscriptions-shipped/index.php +++ b/demo/paypal-checkout-subscriptions-shipped/index.php @@ -2,25 +2,6 @@ require_once('../../includes/config.php'); require_once('../../vendor/autoload.php'); -/** - * Setup configuration for the PayPal library using vars from the config file. - * Then load the PayPal object into $PayPal - */ -$PayPalConfig = array( - 'Sandbox' => $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPalCommonFunctions = new angelleye\PayPal\PayPalCommonFunctions($PayPalConfig); - // Set buyer email in session $_SESSION['buyer_email'] = 'paypal-buyer@angelleye.com'; @@ -97,6 +78,7 @@ +
@@ -194,7 +176,18 @@
- +
$
renderPayPalButton(); ?> + + + + + +
'> +
+ +
+ +
diff --git a/demo/paypal-checkout-subscriptions-shipped/order-complete.php b/demo/paypal-checkout-subscriptions-shipped/order-complete.php index 8b010a3e..526a287e 100644 --- a/demo/paypal-checkout-subscriptions-shipped/order-complete.php +++ b/demo/paypal-checkout-subscriptions-shipped/order-complete.php @@ -3,6 +3,11 @@ * Include our config file and the PayPal library. */ require_once('../../includes/config.php'); + +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} ?> @@ -110,7 +115,8 @@ echo $_SESSION['first_name'] . ' ' . $_SESSION['last_name'] . '
' . $_SESSION['email'] . '
'. $_SESSION['phone_number'] . '
' . - 'Recurring Payment Profile ID : ' .$_SESSION['RecurringProfileId']; + 'PayPal Transaction ID: ' . $_SESSION['paypal_transaction_id'] . '
' . + 'Recurring Payment Profile ID: ' .$_SESSION['RecurringProfileId']; ?>

diff --git a/demo/paypal-checkout-subscriptions-shipped/review.php b/demo/paypal-checkout-subscriptions-shipped/review.php index 013b7541..8f967c4b 100644 --- a/demo/paypal-checkout-subscriptions-shipped/review.php +++ b/demo/paypal-checkout-subscriptions-shipped/review.php @@ -1,5 +1,10 @@ diff --git a/demo/paypal-checkout-subscriptions-shipped/subscription-shippped.js b/demo/paypal-checkout-subscriptions-shipped/subscription-shippped.js new file mode 100644 index 00000000..a5af2c11 --- /dev/null +++ b/demo/paypal-checkout-subscriptions-shipped/subscription-shippped.js @@ -0,0 +1,143 @@ +document.addEventListener("DOMContentLoaded", function () { + const payPalBtnContainer = document.getElementById("paypal-button-container"); + if ( !payPalBtnContainer ) return; + + const checkoutData = JSON.parse(payPalBtnContainer.dataset.checkout); + + async function createOrder() { + try { + const orderPayload = { + intent: "CAPTURE", + purchase_units: [ + { + amount: { + currency_code: "USD", + value: Number(checkoutData.grand_total).toFixed(2), + }, + }, + ], + payment_source: { + paypal: { + experience_context: { + brand_name: "AngellEYE", + shipping_preference: "GET_FROM_FILE", + user_action: "CONTINUE" + } + } + } + }; + + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(orderPayload) + }) + + const data = await response.json(); + if (!data.order_id) { + showPaypalError("Unable to create PayPal order."); + return; + } + + return { orderId: data?.order_id }; + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + function showPaypalError(message) { + const errorContainer = document.getElementById('paypalError'); + if( !errorContainer ) return; + errorContainer.style.display = "block"; + errorContainer.innerHTML = message; + } + + async function captureOrder(data) { + try { + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_capture_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id: data.orderId }), + }); + + const captureResult = await response.json(); + + if (captureResult.status === "COMPLETED") { + window.location.href = `getOrder.php?order_id=${data.orderId}`; + } else { + throw new Error("Payment capture failed."); + } + + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + const paymentSessionOptions = { + async onApprove(data) { + try { + const orderData = await captureOrder({ + orderId: data.orderId, + }); + } catch (error) { + showPaypalError(error.message); + throw error; + } + }, + onCancel() { + location.reload(); + }, + onError(error) { + showPaypalError(error.message); + }, + }; + + async function init() { + try { + const res = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_client_token'); + const { token } = await res.json(); + + const sdkInstance = await window.paypal.createInstance({ + clientToken: token, + components: ['paypal-payments'], + pageType: 'checkout' + }); + + const paymentMethods = await sdkInstance.findEligibleMethods({ + currencyCode: "USD", + }); + + if (paymentMethods.isEligible("paypal")) { + setUpPayPalButton(sdkInstance); + } + } catch (error) { + showPaypalError(`Initialization error: ${error.message}`); + throw error; + } + } + + // Set up standard PayPal button + async function setUpPayPalButton(sdkInstance) { + const paypalPaymentSession = sdkInstance.createPayPalOneTimePaymentSession( + paymentSessionOptions, + ); + + const paypalButton = document.querySelector("paypal-button"); + paypalButton.removeAttribute("hidden"); + + paypalButton.addEventListener("click", async () => { + try { + await paypalPaymentSession.start( + { presentationMode: "auto" }, + createOrder(), + ); + } catch (error) { + showPaypalError(`PayPal payment start error: ${error}`) + } + }); + } + + init(); +}); \ No newline at end of file From 3d3e847d61ab8cb3caf2219f7c7ec04dee8945cc Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 12:42:45 +0530 Subject: [PATCH 139/146] Venmo Checkout --- .../DoExpressCheckoutPayment.php | 123 -------------- .../GetExpressCheckoutDetails.php | 153 ------------------ .../SetExpressCheckout.php | 129 --------------- demo/paypal-venmo-checkout-basic/getOrder.php | 8 +- demo/paypal-venmo-checkout-basic/index.php | 2 +- .../venmo-basic.js | 50 +++++- 6 files changed, 50 insertions(+), 415 deletions(-) delete mode 100644 demo/paypal-venmo-checkout-basic/DoExpressCheckoutPayment.php delete mode 100644 demo/paypal-venmo-checkout-basic/GetExpressCheckoutDetails.php delete mode 100644 demo/paypal-venmo-checkout-basic/SetExpressCheckout.php diff --git a/demo/paypal-venmo-checkout-basic/DoExpressCheckoutPayment.php b/demo/paypal-venmo-checkout-basic/DoExpressCheckoutPayment.php deleted file mode 100644 index 57d3c9f9..00000000 --- a/demo/paypal-venmo-checkout-basic/DoExpressCheckoutPayment.php +++ /dev/null @@ -1,123 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -/** - * Now we'll setup the request params for the final call in the Express Checkout flow. - * This is very similar to SetExpressCheckout except that now we can include values - * for the shipping, handling, and tax amounts, as well as the buyer's name and - * shipping address that we obtained in the GetExpressCheckoutDetails step. - * - * If this information is not included in this final call, it will not be - * available in PayPal's transaction details data. - * - * Once again, the template for DoExpressCheckoutPayment provides - * many more params that are available, but we've stripped everything - * we are not using in this basic demo out. - */ -$DECPFields = array( - 'token' => $_SESSION['paypal_token'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. - 'payerid' => $_SESSION['paypal_payer_id'], // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. -); - -/** - * Just like with SetExpressCheckout, we need to gather our $Payment - * data to pass into our $Payments array. This time we can include - * the shipping, handling, tax, and shipping address details that we - * now have. - */ -$Payments = array(); -$Payment = array( - 'amt' => number_format($_SESSION['shopping_cart']['grand_total'],2), // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. - 'itemamt' => number_format($_SESSION['shopping_cart']['subtotal'],2), // Subtotal of items only. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - 'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'],2), // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. - 'handlingamt' => number_format($_SESSION['shopping_cart']['handling'],2), // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. - 'taxamt' => number_format($_SESSION['shopping_cart']['tax'],2), // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. - 'shiptoname' => $_SESSION['shipping_name'], // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => $_SESSION['shipping_street'], // Required if shipping is included. First street address. 100 char max. - 'shiptocity' => $_SESSION['shipping_city'], // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => $_SESSION['shipping_state'], // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => $_SESSION['shipping_zip'], // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountrycode' => $_SESSION['shipping_country_code'], // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => $_SESSION['phone_number'], // Phone number for shipping address. 20 char max. - 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. -); - -/** - * Here we push our single $Payment into our $Payments array. - */ -array_push($Payments, $Payment); - -/** - * Now we gather all of the arrays above into a single array. - */ -$PayPalRequestData = array( - 'DECPFields' => $DECPFields, - 'Payments' => $Payments, -); - -/** - * Here we are making the call to the DoExpressCheckoutPayment function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ -$PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData); - -/** - * Now we'll setup the request params for the final call in the Express Checkout flow. - * This is very similar to SetExpressCheckout except that now we can include values - * for the shipping, handling, and tax amounts, as well as the buyer's name and - * shipping address that we obtained in the GetExpressCheckoutDetails step. - * - * If this information is not included in this final call, it will not be - * available in PayPal's transaction details data. - * - * Once again, the template for DoExpressCheckoutPayment provides - * many more params that are available, but we've stripped everything - * we are not using in this basic demo out. - */ -if( $PayPalResult['success'] ) { - $_SESSION['paypal_transaction_id'] = isset( $PayPalResult['capture_id'] ) ? $PayPalResult['capture_id'] : ''; - - $captures = ( $PayPalResult['purchase_units'][0]['payments']['captures'][0] ) ? $PayPalResult['purchase_units'][0]['payments']['captures'][0] : []; - $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; - - header('Location: order-complete.php'); -} elseif( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' ) { - $payments_info = isset( $PayPalResult['PAYMENTS'][0] ) ? $PayPalResult['PAYMENTS'][0] : []; - - $_SESSION['paypal_transaction_id'] = isset($payments_info['TRANSACTIONID']) ? $payments_info['TRANSACTIONID'] : ''; - $_SESSION['paypal_fee'] = isset($payments_info['FEEAMT']) ? $payments_info['FEEAMT'] : '0.00'; - - header('Location: order-complete.php'); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-venmo-checkout-basic/GetExpressCheckoutDetails.php b/demo/paypal-venmo-checkout-basic/GetExpressCheckoutDetails.php deleted file mode 100644 index e0cfeb50..00000000 --- a/demo/paypal-venmo-checkout-basic/GetExpressCheckoutDetails.php +++ /dev/null @@ -1,153 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$DECPFields = array( - 'token' => $_SESSION['paypal_token'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. - 'payerid' => '', // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. -); - -/** - * Just like with SetExpressCheckout, we need to gather our $Payment - * data to pass into our $Payments array. This time we can include - * the shipping, handling, tax, and shipping address details that we - * now have. - */ -$Payments = array(); -$Payment = array( - 'amt' => number_format($_SESSION['shopping_cart']['grand_total'],2), // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. - 'itemamt' => number_format($_SESSION['shopping_cart']['subtotal'],2), // Subtotal of items only. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - 'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'],2), // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. - 'handlingamt' => number_format($_SESSION['shopping_cart']['handling'],2), // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. - 'taxamt' => number_format($_SESSION['shopping_cart']['tax'],2), // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. - 'shiptoname' => $_SESSION['shipping_name'], // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => $_SESSION['shipping_street'], // Required if shipping is included. First street address. 100 char max. - 'shiptocity' => $_SESSION['shipping_city'], // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => $_SESSION['shipping_state'], // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => $_SESSION['shipping_zip'], // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountrycode' => $_SESSION['shipping_country_code'], // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => $_SESSION['phone_number'], // Phone number for shipping address. 20 char max. - 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. -); - -/** - * Here we push our single $Payment into our $Payments array. - */ -array_push($Payments, $Payment); - -/** - * Now we gather all of the arrays above into a single array. - */ -$PayPalRequestData = array( - 'DECPFields' => $DECPFields, - 'Payments' => $Payments, -); - -/* - * Here we call GetExpressCheckoutDetails to obtain payer information from PayPal - */ -$PayPalResult = $PayPal->GetExpressCheckoutDetails($PayPalRequestData); - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If the call is successful, we'll save some data we might want to use - * later into session variables. - */ -if( $PayPalResult['success'] || ( $api_upgrade && $PayPalResult['ACK'] && strtoupper($PayPalResult['ACK']) === 'SUCCESS' ) ) { - /** - * Here we'll pull out data from the PayPal response. - */ - $_SESSION['paypal_payer_id'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : '' ) - : ( isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : '' ); - $_SESSION['phone_number'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : '' ) - : ( isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : '' ); - $_SESSION['email'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : '' ) - : ( isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : '' ); - $_SESSION['first_name'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['name']['given_name']) ? $PayPalResult['order']['payer']['name']['given_name'] : '' ) - : ( isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : '' ); - $_SESSION['last_name'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : '' ) - : ( isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : '' ); - $_SESSION['billing_country_code'] = ( ! $api_upgrade ) - ? ( isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : '' ) - : ( isset($PayPalResult['COUNTRYCODE']) ? $PayPalResult['COUNTRYCODE'] : '' ); - - $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; - $shipping = ( ! $api_upgrade ) - ? ( isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : [] ) - : ( isset( $PayPalResult['SHIPPINGDATA'] ) ? $PayPalResult['SHIPPINGDATA'] : [] ); - $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; - $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; - $_SESSION['shipping_city'] = isset($shipping['address']['admin_area_2']) ? $shipping['address']['admin_area_2'] : ''; - $_SESSION['shipping_state'] = isset($shipping['address']['admin_area_1']) ? $shipping['address']['admin_area_1'] : ''; - $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; - $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; - $_SESSION['shipping_country_name'] = 'United States'; - $_SESSION['payment_method_source'] = 'PayPal'; - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - */ - $_SESSION['shopping_cart']['shipping'] = 10.00; - $_SESSION['shopping_cart']['handling'] = 2.50; - $_SESSION['shopping_cart']['tax'] = 1.50; - - $_SESSION['shopping_cart']['grand_total'] = number_format( - $_SESSION['shopping_cart']['subtotal'] - + $_SESSION['shopping_cart']['shipping'] - + $_SESSION['shopping_cart']['handling'] - + $_SESSION['shopping_cart']['tax'],2); - - /** - * Now we will redirect the user to a final review - * page so they can see the shipping/handling/tax - * that has been added to the order. - */ - header('Location: DoExpressCheckoutPayment.php'); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-venmo-checkout-basic/SetExpressCheckout.php b/demo/paypal-venmo-checkout-basic/SetExpressCheckout.php deleted file mode 100644 index 55d2e025..00000000 --- a/demo/paypal-venmo-checkout-basic/SetExpressCheckout.php +++ /dev/null @@ -1,129 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -// Map items from session -$purchase_items = []; -foreach ($_SESSION['venmo_items'] as $item) { - $purchase_items[] = [ - "name" => $item['name'], - "sku" => $item['id'], - "unit_amount" => [ - "currency_code" => "USD", - "value" => number_format($item['price'], 2, '.', '') - ], - "quantity" => (string)$item['qty'] - ]; -} - -// Build the Base Payload -$payload = [ - "intent" => "CAPTURE", - "purchase_units" => [[ - "items" => $purchase_items, - "amount" => [ - "currency_code" => "USD", - "value" => $_SESSION['shopping_cart']['grand_total'], - "breakdown" => [ - "item_total" => [ - "currency_code" => "USD", - "value" => number_format($_SESSION['shopping_cart']['subtotal'], 2, '.', '') - ] - ] - ] - ]], - "payment_source" => [ - "paypal" => [ - "experience_context" => [ - "brand_name" => "Angell EYE", - "shipping_preference" => "GET_FROM_FILE", - "user_action" => "PAY_NOW", - "return_url" => $domain . "demo/paypal-venmo-checkout-basic/GetExpressCheckoutDetails.php", - "cancel_url" => $domain . "demo/paypal-venmo-checkout-basic/", - ], - ] - ], - "payment_method" => [ - "payer_selected" => "PAYPAL", - "payee_preferred" => "IMMEDIATE_PAYMENT_REQUIRED" - ], - "payer" => [ - "email_address" => $_SESSION['buyer_email'] - ] -]; - -/** - * Here we are making the call to the createOrder function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ -$PayPalResult = $PayPal->createOrder($payload); - -/** - * Based on the selected API mode, extract the appropriate redirect URL - * and order identifier from the createOrder response. - * - * - For REST mode (when API upgrade is disabled), PayPal returns an - * `approval_url` for redirection and an `order_id` to track the transaction. - * - For Classic mode (or when API upgrade is enabled), PayPal returns a - * `REDIRECTURL` for redirection and a `TOKEN` that represents the checkout session. - * - * These values are normalized into $redirect_url and $orderId so the - * remaining flow can work consistently regardless of API mode. - */ -$redirect_url = ''; -if( !$api_upgrade ) { - $redirect_url = $PayPalResult['approval_url']; -} else { - $redirect_url = $PayPalResult['REDIRECTURL']; -} - -$orderId = ''; -if( !$api_upgrade ) { - $orderId = $PayPalResult['order_id']; -} else { - $orderId = $PayPalResult['TOKEN']; -} - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If all goes well, we save our token in a session variable so that it's - * readily available for us later, and then redirect the user to PayPal - * using the REDIRECTURL returned by the SetExpressCheckout() function. - */ -if( !empty($redirect_url) ) { - $_SESSION['paypal_token'] = $orderId; - header('Location: ' . $redirect_url); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-venmo-checkout-basic/getOrder.php b/demo/paypal-venmo-checkout-basic/getOrder.php index b7f892a8..bce33686 100644 --- a/demo/paypal-venmo-checkout-basic/getOrder.php +++ b/demo/paypal-venmo-checkout-basic/getOrder.php @@ -32,7 +32,6 @@ /** * Here we'll pull out data from the PayPal response. */ - $_SESSION['paypal_transaction_id'] = $_GET['order_id']; $_SESSION['paypal_payer_id'] = isset($PayPalResult['order']['payer']['payer_id']) ? $PayPalResult['order']['payer']['payer_id'] : ''; $_SESSION['phone_number'] = isset($PayPalResult['order']['payer']['phone']['phone_number']['national_number']) ? $PayPalResult['order']['payer']['phone']['phone_number']['national_number'] : ''; $_SESSION['email'] = isset($PayPalResult['order']['payer']['email_address']) ? $PayPalResult['order']['payer']['email_address'] : ''; @@ -41,6 +40,11 @@ $_SESSION['billing_country_code'] = isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : ''; $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; + + $captures = !empty($purchaseUnit['payments']['captures'][0]) ? $purchaseUnit['payments']['captures'][0] : []; + $_SESSION['paypal_transaction_id'] = isset($captures['id']) ? $captures['id'] : ''; + $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; + $shipping = isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : []; $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; @@ -49,7 +53,7 @@ $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; $_SESSION['shipping_country_name'] = 'United States'; - $_SESSION['payment_method_source'] = 'Venmo'; + $_SESSION['payment_method_source'] = !empty($_GET['payment_source']) ? $_GET['payment_source'] : ''; /** * At this point, we now have the buyer's shipping address available in our app. diff --git a/demo/paypal-venmo-checkout-basic/index.php b/demo/paypal-venmo-checkout-basic/index.php index f5dee5a7..0fdc1290 100644 --- a/demo/paypal-venmo-checkout-basic/index.php +++ b/demo/paypal-venmo-checkout-basic/index.php @@ -168,8 +168,8 @@ - renderPayPalButton(); ?>
'> +
diff --git a/demo/paypal-venmo-checkout-basic/venmo-basic.js b/demo/paypal-venmo-checkout-basic/venmo-basic.js index ede5c1d7..8d9ee9a8 100644 --- a/demo/paypal-venmo-checkout-basic/venmo-basic.js +++ b/demo/paypal-venmo-checkout-basic/venmo-basic.js @@ -3,8 +3,9 @@ document.addEventListener("DOMContentLoaded", function () { if ( !venmoButtonContainer ) return; const checkoutData = JSON.parse(venmoButtonContainer.dataset.checkout); + let selectedPaymentSource = null; - async function createOrder() { + async function createOrder(paymentSource) { try { const items = checkoutData.venmo_items.map(item => ({ name: item.name, @@ -34,7 +35,7 @@ document.addEventListener("DOMContentLoaded", function () { }, ], payment_source: { - venmo: { + [paymentSource]: { experience_context: { brand_name: "AngellEYE", shipping_preference: "GET_FROM_FILE" @@ -79,7 +80,7 @@ document.addEventListener("DOMContentLoaded", function () { const captureResult = await response.json(); if (captureResult.status === "COMPLETED") { - window.location.href = `getOrder.php?order_id=${data.orderId}`; + window.location.href = `getOrder.php?payment_source=${data.paymentSource}&order_id=${data.orderId}`; } else { throw new Error("Payment capture failed."); } @@ -91,11 +92,11 @@ document.addEventListener("DOMContentLoaded", function () { } const paymentSessionOptions = { - fundingSource: "venmo", async onApprove(data) { try { const orderData = await captureOrder({ orderId: data.orderId, + paymentSource: selectedPaymentSource }); } catch (error) { showPaypalError(error.message); @@ -117,12 +118,18 @@ document.addEventListener("DOMContentLoaded", function () { const sdkInstance = await window.paypal.createInstance({ clientToken: token, - components: ["venmo-payments"], + components: ["paypal-payments", "venmo-payments"], }); const paymentMethods = await sdkInstance.findEligibleMethods({ currencyCode: "USD" }); + + const isPayPalEligible = paymentMethods.isEligible("paypal"); + if (isPayPalEligible) { + setupPayPalButton(sdkInstance); + } + const isVenmoEligible = paymentMethods.isEligible("venmo"); if (isVenmoEligible) { setupVenmoButton(sdkInstance); @@ -133,6 +140,34 @@ document.addEventListener("DOMContentLoaded", function () { } } + async function setupPayPalButton(sdkInstance) { + const paypalPaymentSession = sdkInstance.createPayPalOneTimePaymentSession( + paymentSessionOptions, + ); + + // Get reference to the Venmo button element + const paypalButton = document.querySelector("#paypal-button"); + + // Show the button since Venmo is eligible + paypalButton.removeAttribute("hidden"); + + paypalButton.addEventListener("click", async () => { + try { + selectedPaymentSource = "paypal"; + + // Start the payment session + await paypalPaymentSession.start({ + presentationMode: "auto" + }, + createOrder('paypal') + ); + } catch (error) { + showPaypalError(`Error: ${error.message}`); + throw error; + } + }); + } + async function setupVenmoButton(sdkInstance) { const venmoPaymentSession = sdkInstance.createVenmoOneTimePaymentSession( paymentSessionOptions, @@ -146,11 +181,12 @@ document.addEventListener("DOMContentLoaded", function () { venmoButton.addEventListener("click", async () => { try { - // Start the payment session + selectedPaymentSource = "venmo"; + await venmoPaymentSession.start({ presentationMode: "auto" }, - createOrder() + createOrder('venmo') ); } catch (error) { showPaypalError(`Error: ${error.message}`); From 315bddae0050280e9d2edf488b480d3e739a1680 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 15:55:44 +0530 Subject: [PATCH 140/146] PayLater Order --- demo/assets/css/style.css | 8 + demo/paypal-pay-later/checkout-page.php | 13 +- demo/paypal-pay-later/createOrder.php | 132 --------- demo/paypal-pay-later/getOrder.php | 7 + demo/paypal-pay-later/index.php | 1 - demo/paypal-pay-later/paylater.js | 368 ++++++++++++++++-------- demo/paypal-pay-later/review.php | 1 - 7 files changed, 278 insertions(+), 252 deletions(-) delete mode 100644 demo/paypal-pay-later/createOrder.php diff --git a/demo/assets/css/style.css b/demo/assets/css/style.css index caa1ff27..7bae6911 100755 --- a/demo/assets/css/style.css +++ b/demo/assets/css/style.css @@ -468,6 +468,14 @@ body.cart-page .quantity-controls { margin-top: 20px; word-break: break-all; } +#paylater-button-container { + text-align: right; + margin-top: 10px; +} +#paylater-button-container #paypalError { + text-align: right; + margin-bottom: 10px; + } #pay-button { font-style: normal; } diff --git a/demo/paypal-pay-later/checkout-page.php b/demo/paypal-pay-later/checkout-page.php index 7457c8e3..1a45bd48 100644 --- a/demo/paypal-pay-later/checkout-page.php +++ b/demo/paypal-pay-later/checkout-page.php @@ -54,13 +54,19 @@ */ $subtotal = $PayPalCommonFunctions->calculate_subtotal($items); $_SESSION['shopping_cart'] = [ - 'paylater_items' => $items, + 'paylater_items' => $items, 'subtotal' => $subtotal, 'shipping' => 10.00, 'handling' => 2.50, ]; $_SESSION['shopping_cart']['tax'] = number_format(($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling']) * 0.08, 2); $_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'],2); + +$checkoutData = [ + 'payer' => $_SESSION['payer'], + 'billing' => $_SESSION['billing'], + 'cart' => $_SESSION['shopping_cart'] +]; ?> @@ -188,9 +194,10 @@ amount="" currency-code="USD"> - +
diff --git a/demo/paypal-pay-later/createOrder.php b/demo/paypal-pay-later/createOrder.php deleted file mode 100644 index 72d37aa1..00000000 --- a/demo/paypal-pay-later/createOrder.php +++ /dev/null @@ -1,132 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -/** - * Build PayPal items array from shopping cart session - */ -$items = []; -$currency = 'USD'; -foreach ($_SESSION['shopping_cart']['paylater_items'] as $id => $item) { - $items[] = [ - 'name' => $item['name'], - 'unit_amount' => [ - 'currency_code' => $currency, - 'value' => number_format($item['price'], 2, '.', '') - ], - 'quantity' => (string) $item['qty'] - ]; -} - -/** - * Amount breakdown required for Pay Later and order validation - */ -$breakdown = [ - 'item_total' => [ - 'currency_code' => $currency, - 'value' => number_format($_SESSION['shopping_cart']['subtotal'], 2) - ], - 'shipping' => [ - 'currency_code' => $currency, - 'value' => number_format($_SESSION['shopping_cart']['shipping'], 2) - ], - 'handling' => [ - 'currency_code' => $currency, - 'value' => number_format($_SESSION['shopping_cart']['handling'], 2) - ], - 'tax_total' => [ - 'currency_code' => $currency, - 'value' => number_format($_SESSION['shopping_cart']['tax'], 2) - ] -]; - -$_SESSION['reference_id'] = uniqid('ORDER-'); - -/** - * Create PayPal order payload - */ -$orderPayload = [ - 'intent' => 'CAPTURE', - 'payment_method' => [ - 'payer_selected' => 'PAYPAL', - ], - 'purchase_units' => [ - [ - 'reference_id' => $_SESSION['reference_id'], - 'invoice_id' => uniqid('INV-'), - 'amount' => [ - 'currency_code' => $currency, - 'value' => number_format($_SESSION['shopping_cart']['grand_total'], 2, '.', ''), - 'breakdown' => $breakdown - ], - 'items' => $items, - 'shipping' => [ - 'name' => [ - 'full_name' => $_SESSION['payer']['firstname'] . ' ' . $_SESSION['payer']['lastname'] - ], - 'address' => [ - 'address_line_1' => $_SESSION['billing']['street'], - 'admin_area_2' => $_SESSION['billing']['city'], - 'admin_area_1' => $_SESSION['billing']['state'], - 'postal_code' => $_SESSION['billing']['zip'], - 'country_code' => $_SESSION['billing']['countrycode'] - ], - 'email_address' => $_SESSION['payer']['email'] - ] - ] - ], - 'payment_source' => [ - 'paypal' => [ - 'experience_context' => [ - 'return_url' => $domain . 'demo/paypal-pay-later/getOrder.php', - 'cancel_url' => $domain . 'demo/paypal-pay-later/', - 'shipping_preference' => 'SET_PROVIDED_ADDRESS', - 'user_action' => 'PAY_NOW', - ] - ] - ] -]; - -/** - * Create PayPal order - */ -$PayPalResult = $PayPal->createOrder($orderPayload); - -/** - * Handle PayPal response - */ -if ( $PayPalResult['success'] ) { - // Store order ID in session - $_SESSION['paypal_token'] = $PayPalResult['order_id']; - - // Redirect buyer to PayPal approval page - header('Location: ' . $PayPalResult['approval_url']); -} else { - // Store errors and redirect to error page - $_SESSION['paypal_errors'] = $PayPalResult['errors']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-pay-later/getOrder.php b/demo/paypal-pay-later/getOrder.php index a7a07054..14422909 100644 --- a/demo/paypal-pay-later/getOrder.php +++ b/demo/paypal-pay-later/getOrder.php @@ -26,6 +26,9 @@ ); $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); +// get order ID +$_SESSION['paypal_token'] = !empty($_GET['order_id']) ? $_GET['order_id'] : ''; + $PayPalResult = $PayPal->getOrder($_SESSION['paypal_token']); if ( $PayPalResult['success'] ) { @@ -40,6 +43,10 @@ $_SESSION['billing_country_code'] = isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : ''; $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; + + // Get reference id for the patch order + $_SESSION['reference_id'] = !empty($purchaseUnit['reference_id']) ? $purchaseUnit['reference_id'] : ''; + $shipping = isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : []; $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; diff --git a/demo/paypal-pay-later/index.php b/demo/paypal-pay-later/index.php index f0ec7b78..1a608ad4 100644 --- a/demo/paypal-pay-later/index.php +++ b/demo/paypal-pay-later/index.php @@ -23,7 +23,6 @@ 'countrycode' => 'US', // Required. Country code. 'zip' => '33770', // Required. Postal code of payer. ); - ?> diff --git a/demo/paypal-pay-later/paylater.js b/demo/paypal-pay-later/paylater.js index e81d8db4..39410a2f 100644 --- a/demo/paypal-pay-later/paylater.js +++ b/demo/paypal-pay-later/paylater.js @@ -1,116 +1,232 @@ document.addEventListener('DOMContentLoaded', function () { - // Initialize PayPal Pay Later Messages on load - initPayPalMessages(); - // --- DOM ELEMENT SELECTORS --- const quantityControls = document.querySelectorAll('.quantity-controls'); - if (!quantityControls.length) return; - - // Cart-specific total elements - const isCartPage = document.querySelector('.cart-page'); - const cartSubtotalEl = document.querySelector('.cart-subtotal-value'); - const cartShippingEl = document.querySelector('.cart-shipping'); - const cartHandlingEl = document.querySelector('.cart-handling'); - const cartTaxEl = document.querySelector('.cart-tax'); - const cartTotalEl = document.querySelector('.cart-total-value'); + if ( quantityControls.length > 0 ) { + // Cart-specific total elements + const isCartPage = document.querySelector('.cart-page'); + const cartSubtotalEl = document.querySelector('.cart-subtotal-value'); + const cartShippingEl = document.querySelector('.cart-shipping'); + const cartHandlingEl = document.querySelector('.cart-handling'); + const cartTaxEl = document.querySelector('.cart-tax'); + const cartTotalEl = document.querySelector('.cart-total-value'); + + /** + * INITIALIZE QUANTITY STEPPERS + * Iterates through every quantity selector (Plus/Minus buttons) + */ + quantityControls.forEach(stepper => { + const valueEl = stepper.querySelector('.qty-value'); + const inputEl = stepper.querySelector('input[type="hidden"]'); + const plusBtn = stepper.querySelector('.qty-btn.plus'); + const minusBtn = stepper.querySelector('.qty-btn.minus'); + + if (!valueEl || !inputEl) return; + + let value = parseInt(valueEl.textContent, 10) || 1; + + // Cart-only elements + const row = isCartPage ? stepper.closest('.cart-item') : null; + const price = row ? parseFloat(row.dataset.price) : null; + const lineTotalEl = row ? row.querySelector('.line-total span') : null; + + // Extract product ID from hidden input name: qty[123_abc] + const match = inputEl.name.match(/\[(.*?)\]/); + const itemId = match ? match[1] : null; + + function updateUI() { + // Always update quantity + valueEl.textContent = value; + inputEl.value = value; + + // Cart-only pricing logic + if (isCartPage && row && lineTotalEl) { + lineTotalEl.textContent = (price * value).toFixed(2); + recalculateCartTotal(); + + // Update Quantity in Session + if (itemId) { + syncQtyToSession(itemId, value); + } + } + } + + plusBtn?.addEventListener('click', () => { + value++; + updateUI(); + }); + + minusBtn?.addEventListener('click', () => { + if (value > 1) { + value--; + updateUI(); + } + }); + }); + + /** + * Recalculates the entire cart total based on current quantities in the DOM. + * Triggers whenever a quantity is changed. + */ + function recalculateCartTotal() { + if (!isCartPage || !cartSubtotalEl || !cartShippingEl || !cartHandlingEl || !cartTaxEl || !cartTotalEl) return; + + let subtotal = 0; + + // Sum up line totals for all items + document.querySelectorAll('.cart-item').forEach(row => { + const price = parseFloat(row.dataset.price); + const qty = parseInt(row.querySelector('.qty-value').textContent, 10); + subtotal += price * qty; + }); + + // Parse fixed costs (Shipping, Tax, etc.), removing currency symbols + const shipping = parseFloat(cartShippingEl.textContent.replace(/[^0-9.-]+/g, "")) || 0; + const handling = parseFloat(cartHandlingEl.textContent.replace(/[^0-9.-]+/g, "")) || 0; + const tax = parseFloat(cartTaxEl.textContent.replace(/[^0-9.-]+/g, "")) || 0; + + // Calculate Final Total + const finalTotal = subtotal + shipping + handling + tax; + + // Update the UI with formatted decimals + cartSubtotalEl.textContent = subtotal.toFixed(2); + cartTotalEl.textContent = finalTotal.toFixed(2); + + if (window.updatePayLaterAmount) { + window.updatePayLaterAmount(finalTotal); + } + } + + /** + * Sends the updated quantity to the server via AJAX. + * Syncs the PHP $_SESSION with the user's UI changes. + */ + function syncQtyToSession(itemId, qty) { + fetch('cart-update-ajax.php', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ id: itemId, qty: qty }) + }); + } + } - /** - * Recalculates the entire cart total based on current quantities in the DOM. - * Triggers whenever a quantity is changed. - */ - function recalculateCartTotal() { - if (!isCartPage || !cartSubtotalEl || !cartShippingEl || !cartHandlingEl || !cartTaxEl || !cartTotalEl) return; + // CreateOrder and PayLater + let checkoutData = null; + const payLaterBtnContainer = document.getElementById("paylater-button-container"); + if ( payLaterBtnContainer !== undefined && payLaterBtnContainer !== null ) { + checkoutData = JSON.parse(payLaterBtnContainer.dataset.checkout); + } - let subtotal = 0; + async function createOrder() { + try { + const checkoutCartData = checkoutData.cart; + const checkoutBillingData = checkoutData.billing; + const checkoutPayerData = checkoutData.payer; - // Sum up line totals for all items - document.querySelectorAll('.cart-item').forEach(row => { - const price = parseFloat(row.dataset.price); - const qty = parseInt(row.querySelector('.qty-value').textContent, 10); - subtotal += price * qty; - }); + const items = Object.entries(checkoutCartData.paylater_items).map(([sku, item]) => ({ + name: item.name, + sku: sku, + unit_amount: { + currency_code: "USD", + value: Number(item.price).toFixed(2) + }, + quantity: item.qty.toString(), + })); - // Parse fixed costs (Shipping, Tax, etc.), removing currency symbols - const shipping = parseFloat(cartShippingEl.textContent.replace(/[^0-9.-]+/g, "")) || 0; - const handling = parseFloat(cartHandlingEl.textContent.replace(/[^0-9.-]+/g, "")) || 0; - const tax = parseFloat(cartTaxEl.textContent.replace(/[^0-9.-]+/g, "")) || 0; + const orderPayload = { + intent: "CAPTURE", + payment_method: { + payer_selected: "PAYPAL" + }, + purchase_units: [ + { + reference_id: "ORDER-" + Date.now(), + invoice_id: "INV-" + Date.now(), + amount: { + currency_code: "USD", + value: Number(checkoutCartData.grand_total).toFixed(2), + breakdown: { + item_total: { + currency_code: "USD", + value: Number(checkoutCartData.subtotal).toFixed(2), + }, + shipping: { + currency_code: "USD", + value: Number(checkoutCartData.shipping).toFixed(2), + }, + handling: { + currency_code: "USD", + value: Number(checkoutCartData.handling).toFixed(2), + }, + tax_total: { + currency_code: "USD", + value: Number(checkoutCartData.tax).toFixed(2), + } + }, + }, + items: items, + shipping: { + name: { + full_name: checkoutPayerData.firstname + ' ' + checkoutPayerData.lastname + }, + address: { + address_line_1: checkoutBillingData.street, + admin_area_2: checkoutBillingData.city, + admin_area_1: checkoutBillingData.state, + postal_code: checkoutBillingData.zip, + country_code: checkoutBillingData.countrycode + }, + email_address: checkoutPayerData.email + }, + }, + ], + payment_source: { + paypal: { + experience_context: { + brand_name: "AngellEYE", + shipping_preference: "SET_PROVIDED_ADDRESS" + } + } + } + }; - // Calculate Final Total - const finalTotal = subtotal + shipping + handling + tax; + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(orderPayload) + }) - // Update the UI with formatted decimals - cartSubtotalEl.textContent = subtotal.toFixed(2); - cartTotalEl.textContent = finalTotal.toFixed(2); + const data = await response.json(); + if (!data.order_id) { + showPaypalError("Unable to create PayPal order."); + return; + } - if (window.updatePayLaterAmount) { - window.updatePayLaterAmount(finalTotal); + return { orderId: data?.order_id }; + } catch (error) { + showPaypalError(error.message); + throw error; } } - /** - * Sends the updated quantity to the server via AJAX. - * Syncs the PHP $_SESSION with the user's UI changes. - */ - function syncQtyToSession(itemId, qty) { - fetch('cart-update-ajax.php', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ id: itemId, qty: qty }) - }); + function showPaypalError(message) { + const errorContainer = document.getElementById('paypalError'); + if( !errorContainer ) return; + errorContainer.style.display = "block"; + errorContainer.innerHTML = message; } - /** - * INITIALIZE QUANTITY STEPPERS - * Iterates through every quantity selector (Plus/Minus buttons) - */ - quantityControls.forEach(stepper => { - const valueEl = stepper.querySelector('.qty-value'); - const inputEl = stepper.querySelector('input[type="hidden"]'); - const plusBtn = stepper.querySelector('.qty-btn.plus'); - const minusBtn = stepper.querySelector('.qty-btn.minus'); - - if (!valueEl || !inputEl) return; - - let value = parseInt(valueEl.textContent, 10) || 1; - - // Cart-only elements - const row = isCartPage ? stepper.closest('.cart-item') : null; - const price = row ? parseFloat(row.dataset.price) : null; - const lineTotalEl = row ? row.querySelector('.line-total span') : null; - - // Extract product ID from hidden input name: qty[123_abc] - const match = inputEl.name.match(/\[(.*?)\]/); - const itemId = match ? match[1] : null; - - function updateUI() { - // Always update quantity - valueEl.textContent = value; - inputEl.value = value; - - // Cart-only pricing logic - if (isCartPage && row && lineTotalEl) { - lineTotalEl.textContent = (price * value).toFixed(2); - recalculateCartTotal(); - - // Update Quantity in Session - if (itemId) { - syncQtyToSession(itemId, value); - } - } - } - - plusBtn?.addEventListener('click', () => { - value++; - updateUI(); - }); - - minusBtn?.addEventListener('click', () => { - if (value > 1) { - value--; - updateUI(); - } - }); - }); + // Initialize paymentSessionOptions for later use + const paymentSessionOptions = { + async onApprove(data) { + window.location.href = `getOrder.php?order_id=${data.orderId}`; + }, + onCancel() { + location.reload(); + }, + onError(error) { + showPaypalError(error.message); + }, + }; /** * PAYPAL V6 SDK INITIALIZATION @@ -127,23 +243,12 @@ document.addEventListener('DOMContentLoaded', function () { pageType: 'checkout', }); - if (document.body.classList.contains('checkout-page')) { - const paymentMethods = await sdkInstance.findEligibleMethods({ - currencyCode: "USD", - }); - - if (paymentMethods.isEligible("paylater")) { - const payLaterPaymentMethodDetails = paymentMethods.getDetails("paylater"); - const { productCode, countryCode } = payLaterPaymentMethodDetails; - const payLaterButton = document.querySelector("paypal-pay-later-button"); - - const messagesInstance = sdkInstance.createPayPalMessages(); + const paymentMethods = await sdkInstance.findEligibleMethods({ + currencyCode: "USD", + }); - // Configure button with Pay Later specific details - payLaterButton.productCode = productCode; - payLaterButton.countryCode = countryCode; - payLaterButton.removeAttribute("hidden"); - } + if (paymentMethods.isEligible("paylater")) { + setUpPayLaterButton(sdkInstance, paymentMethods); } // This function is exposed globally to be called by recalculateCartTotal() @@ -154,7 +259,40 @@ document.addEventListener('DOMContentLoaded', function () { } }; } catch (error) { - console.error("PayPal Message Init Error:", error); + showPaypalError(`PayPal Message Init Error: ${error}`) } } + + // Set up standard PayPal button + async function setUpPayLaterButton(sdkInstance, paymentMethods) { + const payLaterPaymentMethodDetails = paymentMethods.getDetails("paylater"); + const { productCode, countryCode } = payLaterPaymentMethodDetails; + + // Initialize PayLater Messaging + const messagesInstance = sdkInstance.createPayPalMessages(); + + const paypalPaymentSession = sdkInstance.createPayLaterOneTimePaymentSession( + paymentSessionOptions, + ); + + const payLaterButton = document.querySelector("paypal-pay-later-button"); + if ( !payLaterButton ) return; + + payLaterButton.productCode = productCode; + payLaterButton.countryCode = countryCode; + payLaterButton.removeAttribute("hidden"); + payLaterButton.addEventListener("click", async () => { + try { + await paypalPaymentSession.start( + { presentationMode: "auto" }, + createOrder(), + ); + } catch (error) { + showPaypalError(`PayPal payment start error: ${error}`) + } + }); + } + + // Initialize PayPal Pay Later Messages on load + initPayPalMessages(); }); \ No newline at end of file diff --git a/demo/paypal-pay-later/review.php b/demo/paypal-pay-later/review.php index 561d1101..72720465 100644 --- a/demo/paypal-pay-later/review.php +++ b/demo/paypal-pay-later/review.php @@ -65,7 +65,6 @@

Order Review

Here we display a final review to the buyer now that we've calculated shipping, handling, and tax. The billing and shipping information provided here is what we obtained in the getOrder response.

-

The payment has not been processed at this point because we have not yet called the final captureOrder API. That is what will happen when we click the "Complete Order" button below.

From bdea9fa4600e38f620dc1618a04520c741cfc936 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 16:39:22 +0530 Subject: [PATCH 141/146] Minor Change --- demo/paypal-checkout-basic/basic-paypal.js | 1 + demo/paypal-venmo-checkout-basic/venmo-basic.js | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/demo/paypal-checkout-basic/basic-paypal.js b/demo/paypal-checkout-basic/basic-paypal.js index a5af2c11..1f4ac1d3 100644 --- a/demo/paypal-checkout-basic/basic-paypal.js +++ b/demo/paypal-checkout-basic/basic-paypal.js @@ -107,6 +107,7 @@ document.addEventListener("DOMContentLoaded", function () { const paymentMethods = await sdkInstance.findEligibleMethods({ currencyCode: "USD", + paymentFlow: "VAULT_WITH_PAYMENT", }); if (paymentMethods.isEligible("paypal")) { diff --git a/demo/paypal-venmo-checkout-basic/venmo-basic.js b/demo/paypal-venmo-checkout-basic/venmo-basic.js index 8d9ee9a8..c8be5fd1 100644 --- a/demo/paypal-venmo-checkout-basic/venmo-basic.js +++ b/demo/paypal-venmo-checkout-basic/venmo-basic.js @@ -122,7 +122,8 @@ document.addEventListener("DOMContentLoaded", function () { }); const paymentMethods = await sdkInstance.findEligibleMethods({ - currencyCode: "USD" + currencyCode: "USD", + paymentFlow: "VAULT_WITH_PAYMENT", }); const isPayPalEligible = paymentMethods.isEligible("paypal"); From a25afdd3ceab7be2b44d0a9a3630617ec62dd44d Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 17:14:49 +0530 Subject: [PATCH 142/146] Minor CHanges --- demo/paypal-checkout-advanced-credit-cards/acdc.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/demo/paypal-checkout-advanced-credit-cards/acdc.js b/demo/paypal-checkout-advanced-credit-cards/acdc.js index c2a9aef6..3d99b817 100644 --- a/demo/paypal-checkout-advanced-credit-cards/acdc.js +++ b/demo/paypal-checkout-advanced-credit-cards/acdc.js @@ -164,7 +164,11 @@ document.addEventListener("DOMContentLoaded", function () { components: ["card-fields"], }); - const paymentMethods = await sdkInstance.findEligibleMethods(); + const paymentMethods = await sdkInstance.findEligibleMethods({ + currencyCode: "USD", + paymentFlow: "VAULT_WITH_PAYMENT", + }); + const isCardFieldsEligible = paymentMethods.isEligible("advanced_cards"); if (isCardFieldsEligible) { setupCardFields(sdkInstance); From 4eb4076b80b61b40c74cf6b6cd1803bd3198cddd Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 19:49:52 +0530 Subject: [PATCH 143/146] Vaulting --- .../DoExpressCheckoutPayment.php | 134 --------------- .../DoReferenceTransaction.php | 124 ++++++-------- .../GetExpressCheckoutDetails.php | 140 ---------------- .../SetExpressCheckout.php | 129 --------------- demo/paypal-checkout-vaulting/createOrder.php | 10 ++ .../getCapturedOrder.php | 5 + demo/paypal-checkout-vaulting/index.php | 16 +- .../order-complete.php | 5 + demo/paypal-checkout-vaulting/review.php | 10 +- demo/paypal-checkout-vaulting/vaulting.js | 153 ++++++++++++++++++ src/angelleye/PayPal/PayPalREST.php | 21 +-- src/angelleye/PayPal/api/paypal-api.php | 25 ++- 12 files changed, 267 insertions(+), 505 deletions(-) delete mode 100644 demo/paypal-checkout-vaulting/DoExpressCheckoutPayment.php delete mode 100644 demo/paypal-checkout-vaulting/GetExpressCheckoutDetails.php delete mode 100644 demo/paypal-checkout-vaulting/SetExpressCheckout.php create mode 100644 demo/paypal-checkout-vaulting/vaulting.js diff --git a/demo/paypal-checkout-vaulting/DoExpressCheckoutPayment.php b/demo/paypal-checkout-vaulting/DoExpressCheckoutPayment.php deleted file mode 100644 index 91c268e0..00000000 --- a/demo/paypal-checkout-vaulting/DoExpressCheckoutPayment.php +++ /dev/null @@ -1,134 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id_2, - 'ClientSecret' => $rest_client_secret_2, - 'MerchantID' => $rest_merchant_id, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -/** - * Now we'll setup the request params for the final call in the Express Checkout flow. - * This is very similar to SetExpressCheckout except that now we can include values - * for the shipping, handling, and tax amounts, as well as the buyer's name and - * shipping address that we obtained in the GetExpressCheckoutDetails step. - * - * If this information is not included in this final call, it will not be - * available in PayPal's transaction details data. - * - * Once again, the template for DoExpressCheckoutPayment provides - * many more params that are available, but we've stripped everything - * we are not using in this basic demo out. - */ -$DECPFields = array( - 'token' => $_SESSION['paypal_token'], // Required. A timestamped token, the value of which was returned by a previous SetExpressCheckout call. - 'payerid' => $_SESSION['paypal_payer_id'], // Required. Unique PayPal customer id of the payer. Returned by GetExpressCheckoutDetails, or if you used SKIPDETAILS it's returned in the URL back to your RETURNURL. -); - -/** - * Just like with SetExpressCheckout, we need to gather our $Payment - * data to pass into our $Payments array. This time we can include - * the shipping, handling, tax, and shipping address details that we - * now have. - */ -$Payments = array(); -$Payment = array( - 'amt' => number_format($_SESSION['shopping_cart']['grand_total'],2), // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. - 'itemamt' => number_format($_SESSION['shopping_cart']['subtotal'],2), // Subtotal of items only. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - 'shippingamt' => number_format($_SESSION['shopping_cart']['shipping'],2), // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. - 'handlingamt' => number_format($_SESSION['shopping_cart']['handling'],2), // Total handling costs for this order. If you specify HANDLINGAMT you mut also specify a value for ITEMAMT. - 'taxamt' => number_format($_SESSION['shopping_cart']['tax'],2), // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. - 'shiptoname' => $_SESSION['shipping_name'], // Required if shipping is included. Person's name associated with this address. 32 char max. - 'shiptostreet' => $_SESSION['shipping_street'], // Required if shipping is included. First street address. 100 char max. - 'shiptocity' => $_SESSION['shipping_city'], // Required if shipping is included. Name of city. 40 char max. - 'shiptostate' => $_SESSION['shipping_state'], // Required if shipping is included. Name of state or province. 40 char max. - 'shiptozip' => $_SESSION['shipping_zip'], // Required if shipping is included. Postal code of shipping address. 20 char max. - 'shiptocountrycode' => $_SESSION['shipping_country_code'], // Required if shipping is included. Country code of shipping address. 2 char max. - 'shiptophonenum' => $_SESSION['phone_number'], // Phone number for shipping address. 20 char max. - 'paymentaction' => 'Sale', // How you want to obtain the payment. When implementing parallel payments, this field is required and must be set to Order. -); - -/** - * Here we push our single $Payment into our $Payments array. - */ -array_push($Payments, $Payment); - -/** - * Now we gather all of the arrays above into a single array. - */ -$PayPalRequestData = array( - 'DECPFields' => $DECPFields, - 'Payments' => $Payments, -); - -/** - * Here we are making the call to the DoExpressCheckoutPayment function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ -$PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData); - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If the call is successful, we'll save some data we might want to use - * later into session variables, and then redirect to our final - * thank you / receipt page. - */ -if($PayPal->APICallSuccessful($PayPalResult['ACK'])) -{ - /** - * Once again, since Express Checkout allows for multiple payments in a single transaction, - * the DoExpressCheckoutPayment response is setup to provide data for each potential payment. - * As such, we need to loop through all the payment info in the response. - * - * The library helps us do this using the GetExpressCheckoutPaymentInfo() method. We'll - * load our $payments_info using that method, and then loop through the results to pull - * out our details for the transaction. - * - * Again, in this case we are you only working with a single payment, but we'll still - * loop through the results accordingly. - * - * Here, we're only pulling out the PayPal transaction ID, billing agreement ID, and fee amount, - * but you may refer to the API reference for all the additional parameters you have available at - * this point. - * - * https://developer.paypal.com/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/ - */ - $_SESSION['paypal_billing_agreement_id'] = isset($PayPalResult['BILLINGAGREEMENTID']) ? $PayPalResult['BILLINGAGREEMENTID'] : ''; - - $payments_info = $PayPal->GetExpressCheckoutPaymentInfo($PayPalResult); - - foreach($payments_info as $payment_info) - { - $_SESSION['paypal_transaction_id'] = isset($payment_info['TRANSACTIONID']) ? $payment_info['TRANSACTIONID'] : ''; - $_SESSION['paypal_fee'] = isset($payment_info['FEEAMT']) ? $payment_info['FEEAMT'] : ''; - } - - header('Location: order-complete.php'); -} -else -{ - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-checkout-vaulting/DoReferenceTransaction.php b/demo/paypal-checkout-vaulting/DoReferenceTransaction.php index 75826c1c..c66fae39 100644 --- a/demo/paypal-checkout-vaulting/DoReferenceTransaction.php +++ b/demo/paypal-checkout-vaulting/DoReferenceTransaction.php @@ -5,6 +5,11 @@ require_once('../../includes/config.php'); require_once('../../vendor/autoload.php'); +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} + /** * Setup configuration for the PayPal library using vars from the config file. * Then load the PayPal object into $PayPal @@ -13,9 +18,6 @@ 'Sandbox' => $sandbox, 'PayPalAPIMode' => $api_mode, 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, 'ClientID' => $rest_client_id_2, 'ClientSecret' => $rest_client_secret_2, 'MerchantID' => $rest_merchant_id, @@ -25,89 +27,53 @@ ); $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); -if ( $api_mode === 'classic' ) { - /** - * Now we setup the parameters for the reference transaction. - * This is where we use the transaction ID or billing agreement ID - * from a previous Express Checkout (or Payments Pro) transaction. - */ - $ReferenceID = 'B-20L17406RW402900E'; - - $DRTFields = array( - 'referenceid' => $ReferenceID, // Required. A transaction ID from a previous purchase, such as a credit card charage using DoDirectPayment, or a billing agreement ID - 'paymentaction' => 'Sale', // How you want to obtain payment. Values are: Authorization, Sale - 'ipaddress' => $_SERVER['REMOTE_ADDR'], // IP address of the buyer's browser - ); - - /** - * Here we'll setup the payment details for the reference transaction - * that we are processing. - */ - $PaymentDetails = array( - 'amt' => '10.00', // Required. Total amount of the order, including shipping, handling, and tax. - 'currencycode' => 'USD', // A three-character currency code. Default is USD. - ); +// Vault token ID +$VaultTokenID = '1bm89546xv216635v'; - /** - * Now we gather all of the arrays above into a single array. - */ - $PayPalRequestData = array( - 'DRTFields' => $DRTFields, - 'PaymentDetails' => $PaymentDetails, - ); - - /** - * Here we are making the call to the DoExpressCheckoutPayment function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ - $PayPalResult = $PayPal->DoReferenceTransaction($PayPalRequestData); -} elseif ( $api_mode === 'rest' ) { - // Vault token ID - $VaultTokenID = '1bm89546xv216635v'; - - /** - * Create PayPal order payload - */ - $orderPayload = [ - 'intent' => 'CAPTURE', - 'purchase_units' => [ - [ - 'amount' => [ - 'currency_code' => 'USD', - 'value' => '10.00', +/** + * Create PayPal order payload + */ +$orderPayload = [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ + [ + 'amount' => [ + 'currency_code' => 'USD', + 'value' => '10.00', + ], + 'shipping' => [ + 'name' => [ + 'full_name' => 'John Doe' ], - 'shipping' => [ - 'name' => [ - 'full_name' => 'John Doe' - ], - 'address' => [ - 'address_line_1' => '1 Main St', - 'admin_area_2' => 'San Jose', - 'admin_area_1' => 'CA', - 'postal_code' => '95131', - 'country_code' => 'US' - ] + 'address' => [ + 'address_line_1' => '1 Main St', + 'admin_area_2' => 'San Jose', + 'admin_area_1' => 'CA', + 'postal_code' => '95131', + 'country_code' => 'US' ] ] - ], - 'payment_source' => [ - 'paypal' => [ - 'vault_id' => $VaultTokenID - ] ] - ]; + ], + 'payment_source' => [ + 'paypal' => [ + 'vault_id' => $VaultTokenID + ] + ] +]; + +/** + * Generate unique PayPal request ID + */ +$paypalRequestId = uniqid('pprid_', true); - /** - * Generate unique PayPal request ID - */ - $paypalRequestId = uniqid('pprid_', true); +/** + * Create PayPal order + */ +$PayPalResult = $PayPal->createOrder($orderPayload, $paypalRequestId); - /** - * Create PayPal order - */ - $PayPalResult = $PayPal->createOrder($orderPayload, $paypalRequestId); -} else { - $PayPalResult = [ +if ( !$PayPalResult['success'] ) { + $errors = [ 'success' => false, 'error' => 'Something went wrong while processing the PayPal payment.' ]; diff --git a/demo/paypal-checkout-vaulting/GetExpressCheckoutDetails.php b/demo/paypal-checkout-vaulting/GetExpressCheckoutDetails.php deleted file mode 100644 index d66d4b78..00000000 --- a/demo/paypal-checkout-vaulting/GetExpressCheckoutDetails.php +++ /dev/null @@ -1,140 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id_2, - 'ClientSecret' => $rest_client_secret_2, - 'MerchantID' => $rest_merchant_id, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -if( $api_mode === 'classic' ) { - /** - * Now we pass the PayPal token that we saved to a session variable - * in the SetExpressCheckout.php file into the GetExpressCheckoutDetails - * request. - */ - $PayPalResult = $PayPal->GetExpressCheckoutDetails($_SESSION['paypal_token']); - - /** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If the call is successful, we'll save some data we might want to use - * later into session variables. - */ - if($PayPal->APICallSuccessful($PayPalResult['ACK'])) - { - /** - * Here we'll pull out data from the PayPal response. - * Refer to the PayPal API Reference for all of the variables available - * in $PayPalResult['variablename'] - * - * https://developer.paypal.com/docs/classic/api/merchant/GetExpressCheckoutDetails_API_Operation_NVP/ - * - * Again, Express Checkout allows for parallel payments, so what we're doing here - * is usually the library to parse out the individual payments using the GetPayments() - * method so that we can easily access the data. - * - * We only have a single payment here, which will be the case with most checkouts, - * but we will still loop through the $Payments array returned by the library - * to grab our data accordingly. - */ - $_SESSION['paypal_payer_id'] = isset($PayPalResult['PAYERID']) ? $PayPalResult['PAYERID'] : ''; - $_SESSION['phone_number'] = isset($PayPalResult['PHONENUM']) ? $PayPalResult['PHONENUM'] : ''; - $_SESSION['email'] = isset($PayPalResult['EMAIL']) ? $PayPalResult['EMAIL'] : ''; - $_SESSION['first_name'] = isset($PayPalResult['FIRSTNAME']) ? $PayPalResult['FIRSTNAME'] : ''; - $_SESSION['last_name'] = isset($PayPalResult['LASTNAME']) ? $PayPalResult['LASTNAME'] : ''; - - $payments = $PayPal->GetPayments($PayPalResult); - - foreach($payments as $payment) - { - $_SESSION['shipping_name'] = isset($payment['SHIPTONAME']) ? $payment['SHIPTONAME'] : ''; - $_SESSION['shipping_street'] = isset($payment['SHIPTOSTREET']) ? $payment['SHIPTOSTREET'] : ''; - $_SESSION['shipping_city'] = isset($payment['SHIPTOCITY']) ? $payment['SHIPTOCITY'] : ''; - $_SESSION['shipping_state'] = isset($payment['SHIPTOSTATE']) ? $payment['SHIPTOSTATE'] : ''; - $_SESSION['shipping_zip'] = isset($payment['SHIPTOZIP']) ? $payment['SHIPTOZIP'] : ''; - $_SESSION['shipping_country_code'] = isset($payment['SHIPTOCOUNTRYCODE']) ? $payment['SHIPTOCOUNTRYCODE'] : ''; - $_SESSION['shipping_country_name'] = isset($payment['SHIPTOCOUNTRYNAME']) ? $payment['SHIPTOCOUNTRYNAME'] : ''; - } - - /** - * At this point, we now have the buyer's shipping address available in our app. - * We could now run the data through a shipping calculator to retrieve rate - * information for this particular order. - * - * This would also be the time to calculate any sales tax you may need to - * add to the order, as well as handling fees. - * - * We're going to set static values for these things in our static - * shopping cart, and then re-calculate our grand total. - */ - $_SESSION['shopping_cart']['shipping'] = 10.00; - $_SESSION['shopping_cart']['handling'] = 2.50; - $_SESSION['shopping_cart']['tax'] = 1.50; - - $_SESSION['shopping_cart']['grand_total'] = number_format( - $_SESSION['shopping_cart']['subtotal'] - + $_SESSION['shopping_cart']['shipping'] - + $_SESSION['shopping_cart']['handling'] - + $_SESSION['shopping_cart']['tax'],2); - - /** - * Now we will redirect the user to a final review - * page so they can see the shipping/handling/tax - * that has been added to the order. - */ - header('Location: review.php'); - } -} elseif( $api_mode === 'rest' ) { - $setupToken = isset($_SESSION['paypal_setup_token']) ? $_SESSION['paypal_setup_token'] : ''; - - $getSetupTokenData = $PayPal->getVaultSetupTokenDetails($setupToken); - - if( $getSetupTokenData['success'] && $getSetupTokenData['status'] === 'APPROVED' ) { - $approvedSetupToken = isset( $getSetupTokenData['setup_token'] ) ? $getSetupTokenData['setup_token'] : ''; - - $VaultPaymentTokenData = [ - 'payment_source' => [ - 'token' => [ - 'id' => $approvedSetupToken, - 'type' => 'SETUP_TOKEN' - ], - ] - ]; - - $RESTVaultPaymentTokenData = array( - 'setup_token' => $approvedSetupToken, - 'vault_payment_data' => $VaultPaymentTokenData, - ); - - $PayPalResult = $PayPal->createVaultPaymentToken($RESTVaultPaymentTokenData); - - if( $PayPalResult['success'] ) { - $_SESSION['paypal_vault_token'] = isset($PayPalResult['vault_token']) ? $PayPalResult['vault_token'] : ''; - header('Location: createOrder.php'); - } - } -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-checkout-vaulting/SetExpressCheckout.php b/demo/paypal-checkout-vaulting/SetExpressCheckout.php deleted file mode 100644 index 8ee3416c..00000000 --- a/demo/paypal-checkout-vaulting/SetExpressCheckout.php +++ /dev/null @@ -1,129 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'APIUsername' => $api_username, - 'APIPassword' => $api_password, - 'APISignature' => $api_signature, - 'ClientID' => $rest_client_id_2, - 'ClientSecret' => $rest_client_secret_2, - 'MerchantID' => $rest_merchant_id, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -/** - * Here we are setting up the parameters for a basic Express Checkout flow. - * - * The template provided at ../../vendor/angelleye/paypal-php-library/templates/SetExpressCheckout.php - * contains a lot more parameters that we aren't using here, so I've removed them to keep this clean. - * - * $domain used here is set in the config file. - */ -$SECFields = array( - 'maxamt' => number_format($_SESSION['shopping_cart']['grand_total'] * 2,2), // The expected maximum total amount the order will be, including S&H and sales tax. - 'returnurl' => $domain . 'demo/paypal-checkout-vaulting/GetExpressCheckoutDetails.php', // Required. URL to which the customer will be returned after returning from PayPal. 2048 char max. - 'cancelurl' => $domain . 'demo/paypal-checkout-vaulting/', // Required. URL to which the customer will be returned if they cancel payment on PayPal's site. - 'hdrimg' => 'https://www.angelleye.com/images/angelleye-paypal-header-750x90.jpg', // URL for the image displayed as the header during checkout. Max size of 750x90. Should be stored on an https:// server or you'll get a warning message in the browser. - 'logoimg' => 'https://www.angelleye.com/images/angelleye-logo-190x60.jpg', // A URL to your logo image. Formats: .gif, .jpg, .png. 190x60. PayPal places your logo image at the top of the cart review area. This logo needs to be stored on a https:// server. - 'brandname' => 'Angell EYE', // A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages. 127 char max. - 'customerservicenumber' => '816-555-5555', // Merchant Customer Service number displayed on the PayPal Review page. 16 char max. -); - -/** - * Now we begin setting up our payment(s). - * - * Express Checkout includes the ability to setup parallel payments, - * so we have to populate our $Payments array here accordingly. - * - * For this sample (and in most use cases) we only need a single payment, - * but we still have to populate $Payments with a single $Payment array. - * - * Once again, the template file includes a lot more available parameters, - * but for this basic sample we've removed everything that we're not using, - * so all we have is an amount. - */ -$Payments = array(); -$Payment = array( - 'amt' => $_SESSION['shopping_cart']['grand_total'], // Required. The total cost of the transaction to the customer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. -); - -/** - * Here we push our single $Payment into our $Payments array. - */ -array_push($Payments, $Payment); - -/** - * Now we add the billing agreement parameters so that we can - * process reference transactions for this buyer in the future. - */ -$BillingAgreements = array(); -$Item = array( - 'l_billingtype' => 'MerchantInitiatedBilling', // Required. Type of billing agreement. For recurring payments it must be RecurringPayments. You can specify up to ten billing agreements. For reference transactions, this field must be either: MerchantInitiatedBilling, or MerchantInitiatedBillingSingleSource - 'l_billingagreementdescription' => '', // Required for recurring payments. Description of goods or services associated with the billing agreement. - 'l_paymenttype' => '', // Specifies the type of PayPal payment you require for the billing agreement. Any or IntantOnly - 'l_billingagreementcustom' => '' // Custom annotation field for your own use. 256 char max. -); -array_push($BillingAgreements, $Item); - -/** - * Now we gather all of the arrays above into a single array. - */ -$PayPalRequestData = array( - 'SECFields' => $SECFields, - 'Payments' => $Payments, - 'BillingAgreements' => $BillingAgreements, -); - -$RESTVaultSetupData = array( - 'brand_name' => 'Angell EYE', - 'return_url' => $domain . 'demo/paypal-checkout-vaulting/GetExpressCheckoutDetails.php', - 'cancel_url' => $domain . 'demo/paypal-checkout-vaulting/', -); - -if( $api_mode === 'classic' ) { - /** - * Here we are making the call to the SetExpressCheckout function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ - $PayPalResult = $PayPal->SetExpressCheckout($PayPalRequestData); - - /** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If all goes well, we save our token in a session variable so that it's - * readily available for us later, and then redirect the user to PayPal - * using the REDIRECTURL returned by the SetExpressCheckout() function. - */ - if($PayPal->APICallSuccessful($PayPalResult['ACK'])) { - $_SESSION['paypal_token'] = isset($PayPalResult['TOKEN']) ? $PayPalResult['TOKEN'] : ''; - header('Location: ' . $PayPalResult['REDIRECTURL']); - } -} elseif( $api_mode === 'rest' ) { - $PayPalResult = $PayPal->createVaultSetupToken($RESTVaultSetupData); - - if( $PayPalResult['success'] ) { - $_SESSION['paypal_setup_token'] = isset($PayPalResult['setup_token']) ? $PayPalResult['setup_token'] : ''; - $_SESSION['paypal_customer_id'] = isset($PayPalResult['customer_id']) ? $PayPalResult['customer_id'] : ''; - header('Location: ' . $PayPalResult['approval_url']); - } -} else -{ - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-checkout-vaulting/createOrder.php b/demo/paypal-checkout-vaulting/createOrder.php index 7444fd8b..9cebf51f 100644 --- a/demo/paypal-checkout-vaulting/createOrder.php +++ b/demo/paypal-checkout-vaulting/createOrder.php @@ -5,6 +5,11 @@ require_once('../../includes/config.php'); require_once('../../vendor/autoload.php'); +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} + /** * Setup configuration for the PayPal library using vars from the config file. * Then load the PayPal object into $PayPal @@ -22,6 +27,11 @@ ); $PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); +// GET data +$_SESSION['paypal_setup_token'] = !empty($_GET['setupToken']) ? $_GET['setupToken'] : ''; +$_SESSION['paypal_customer_id'] = !empty($_GET['customerID']) ? $_GET['customerID'] : ''; +$_SESSION['paypal_vault_token'] = !empty($_GET['paymentToken']) ? $_GET['paymentToken'] : ''; + /** * Create PayPal order payload */ diff --git a/demo/paypal-checkout-vaulting/getCapturedOrder.php b/demo/paypal-checkout-vaulting/getCapturedOrder.php index 30f5cc93..c2d1a626 100644 --- a/demo/paypal-checkout-vaulting/getCapturedOrder.php +++ b/demo/paypal-checkout-vaulting/getCapturedOrder.php @@ -5,6 +5,11 @@ require_once('../../includes/config.php'); require_once('../../vendor/autoload.php'); +// Redirect to Pay Later Product Page if API mode is classic +if ($api_mode === 'classic') { + header('Location: ./'); +} + /** * Setup configuration for the PayPal library using vars from the config file. * Then load the PayPal object into $PayPal diff --git a/demo/paypal-checkout-vaulting/index.php b/demo/paypal-checkout-vaulting/index.php index 8460f7cd..4ee45cb0 100644 --- a/demo/paypal-checkout-vaulting/index.php +++ b/demo/paypal-checkout-vaulting/index.php @@ -79,6 +79,9 @@ + + +
@@ -162,7 +165,18 @@
- +
$
renderPayPalButton(); ?> + + + + + +
'> +
+ +
+ +
diff --git a/demo/paypal-checkout-vaulting/order-complete.php b/demo/paypal-checkout-vaulting/order-complete.php index e2d8e3a5..baa4dc60 100644 --- a/demo/paypal-checkout-vaulting/order-complete.php +++ b/demo/paypal-checkout-vaulting/order-complete.php @@ -1,5 +1,10 @@ diff --git a/demo/paypal-checkout-vaulting/review.php b/demo/paypal-checkout-vaulting/review.php index 06d4d4fb..7f4a5932 100644 --- a/demo/paypal-checkout-vaulting/review.php +++ b/demo/paypal-checkout-vaulting/review.php @@ -1,5 +1,10 @@ @@ -129,8 +134,9 @@ $ - - Complete Order + + Complete Order + diff --git a/demo/paypal-checkout-vaulting/vaulting.js b/demo/paypal-checkout-vaulting/vaulting.js new file mode 100644 index 00000000..985dc88d --- /dev/null +++ b/demo/paypal-checkout-vaulting/vaulting.js @@ -0,0 +1,153 @@ +document.addEventListener("DOMContentLoaded", function () { + async function createVaultSetupToken() { + try { + const payloadData = { + payment_source: { + paypal: { + usage_type: "MERCHANT", + customer_type: "CONSUMER", + experience_context: { + brand_name: "AngellEYE", + locale: "en-US", + shipping_preference: "NO_SHIPPING", + return_url: window.location.href, + cancel_url: window.location.href + } + } + } + }; + + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_vault_setup_token&vaulting=true', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payloadData) + }) + + const setupTokenData = await response.json(); + if (!setupTokenData.setup_token) { + showPaypalError("Unable to create Vault Setup Token."); + return; + } + + return { vaultSetupToken: setupTokenData?.setup_token }; + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + function showPaypalError(message) { + const errorContainer = document.getElementById('paypalError'); + if( !errorContainer ) return; + errorContainer.style.display = "block"; + errorContainer.innerHTML = message; + } + + async function createPaymentToken(data) { + try { + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_get_vault_setup_token&vaulting=true', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id: data.vaultSetupToken }), + }); + const getSetupTokenData = await response.json(); + + if (getSetupTokenData.status === "APPROVED") { + const payloadData = { + payment_source: { + token: { + id: getSetupTokenData.setup_token, + type: "SETUP_TOKEN" + } + } + }; + + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_vault_payment_token&vaulting=true', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payloadData) + }) + + const vaultTokenData = await response.json(); + if (!vaultTokenData.vault_token) { + showPaypalError("Unable to create Vault Payment Token."); + return; + } + window.location.href = `createOrder.php?setupToken=${getSetupTokenData.setup_token}&customerID=${getSetupTokenData.customer_id}&paymentToken=${vaultTokenData.vault_token}`; + } else { + throw new Error("Payment capture failed."); + } + + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + const paymentSessionOptions = { + async onApprove(data) { + try { + const orderData = await createPaymentToken({ + vaultSetupToken: data.vaultSetupToken, + }); + } catch (error) { + showPaypalError(error.message); + throw error; + } + }, + onCancel() { + location.reload(); + }, + onError(error) { + showPaypalError(error.message); + }, + }; + + async function init() { + try { + const res = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_client_token'); + const { token } = await res.json(); + + const sdkInstance = await window.paypal.createInstance({ + clientToken: token, + components: ['paypal-payments'], + pageType: 'checkout' + }); + + const paymentMethods = await sdkInstance.findEligibleMethods({ + currencyCode: "USD", + paymentFlow: "VAULT_WITHOUT_PAYMENT", + }); + + if (paymentMethods.isEligible("paypal")) { + setUpPayPalButton(sdkInstance); + } + } catch (error) { + showPaypalError(`Initialization error: ${error.message}`); + throw error; + } + } + + // Set up standard PayPal button + async function setUpPayPalButton(sdkInstance) { + const paypalPaymentSession = sdkInstance.createPayPalSavePaymentSession( + paymentSessionOptions, + ); + + const paypalButton = document.querySelector("paypal-button"); + paypalButton.removeAttribute("hidden"); + + paypalButton.addEventListener("click", async () => { + try { + await paypalPaymentSession.start( + { presentationMode: "auto" }, + createVaultSetupToken(), + ); + } catch (error) { + showPaypalError(`PayPal payment start error: ${error}`) + } + }); + } + + init(); +}); \ No newline at end of file diff --git a/src/angelleye/PayPal/PayPalREST.php b/src/angelleye/PayPal/PayPalREST.php index 161a8d4d..ee67413b 100644 --- a/src/angelleye/PayPal/PayPalREST.php +++ b/src/angelleye/PayPal/PayPalREST.php @@ -1792,23 +1792,7 @@ public function MassPay($DataArray) { */ public function createVaultSetupToken($DataArray) { try { - $payloadData = [ - 'payment_source' => [ - 'paypal' => [ - 'usage_type' => 'MERCHANT', - 'customer_type'=> 'CONSUMER', - 'experience_context' => [ - 'brand_name' => isset($DataArray['brand_name']) ? $DataArray['brand_name'] : 'My Store', - 'locale' => isset($DataArray['locale']) ? $DataArray['locale'] : 'en-US', - 'shipping_preference' => 'NO_SHIPPING', - 'return_url' => isset($DataArray['return_url']) ? $DataArray['return_url'] : '', - 'cancel_url' => isset($DataArray['cancel_url']) ? $DataArray['cancel_url'] : '', - ] - ] - ] - ]; - - $response = $this->makeRequest('/v3/vault/setup-tokens', 'POST', $payloadData, null, false, true); + $response = $this->makeRequest('/v3/vault/setup-tokens', 'POST', $DataArray, null, false, true); if (in_array($response['status_code'], [200, 201])) { return [ @@ -1826,7 +1810,7 @@ public function createVaultSetupToken($DataArray) { 'success' => false, 'error' => 'Failed to create setup token', 'status_code' => isset($response['body']['status']) ? $response['body']['status'] : $response['status_code'], - 'full_response' => $response['body'], + 'errors' => $response['body'], 'raw_response' => $response['raw_response'] ]; } catch (\Exception $e) { @@ -1855,6 +1839,7 @@ public function getVaultSetupTokenDetails($setupToken) { return [ 'success' => true, 'setup_token' => isset($response['body']['id']) ? $response['body']['id'] : '', + 'customer_id' => isset($response['body']['customer']['id']) ? $response['body']['customer']['id'] : '', 'status' => isset($response['body']['status']) ? $response['body']['status'] : $response['status_code'], 'full_response' => $response['body'], 'raw_response' => $response['raw_response'] diff --git a/src/angelleye/PayPal/api/paypal-api.php b/src/angelleye/PayPal/api/paypal-api.php index fc9cab4b..a13aa92d 100644 --- a/src/angelleye/PayPal/api/paypal-api.php +++ b/src/angelleye/PayPal/api/paypal-api.php @@ -3,13 +3,16 @@ require_once('../../../../includes/config.php'); require_once('../../../../autoload.php'); +$vaulting = isset($_GET['vaulting']) ? $_GET['vaulting'] : false; + // Create PayPal object. $PayPalConfig = array( 'Sandbox' => $sandbox, 'PayPalAPIMode' => $api_mode, 'PayPalAPIUpgrade' => $api_upgrade, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, + 'ClientID' => ($vaulting) ? $rest_client_id_2 : $rest_client_id, + 'ClientSecret' => ($vaulting) ? $rest_client_secret_2 : $rest_client_secret, + 'MerchantID' => $rest_merchant_id, 'PrintHeaders' => $print_headers, 'LogResults' => $log_results, 'LogPath' => $log_path, @@ -36,6 +39,24 @@ echo json_encode($capture_response); break; + case 'ae_create_vault_setup_token': + $create_vault_setuptoken_response = $PayPal->createVaultSetupToken($input); + echo json_encode($create_vault_setuptoken_response); + break; + + case 'ae_get_vault_setup_token': + $get_vault_setuptoken_response = $PayPal->getVaultSetupTokenDetails($input['id']); + echo json_encode($get_vault_setuptoken_response); + break; + + case 'ae_create_vault_payment_token': + $vaultPaymentData = [ + 'vault_payment_data' => $input, + ]; + $create_vault_paymenttoken_response = $PayPal->createVaultPaymentToken($vaultPaymentData); + echo json_encode($create_vault_paymenttoken_response); + break; + default: http_response_code(400); echo json_encode(['error' => 'Invalid action']); From 7929f052698cb522d607babc508b2fa7e1b55165 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Mon, 16 Mar 2026 20:30:31 +0530 Subject: [PATCH 144/146] Minor Shipping Callback Fixes --- demo/paypal-checkout-shipping-callback/getOrder.php | 5 +++++ demo/paypal-checkout-shipping-callback/index.php | 1 + demo/paypal-checkout-shipping-callback/shipping-cb.js | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/demo/paypal-checkout-shipping-callback/getOrder.php b/demo/paypal-checkout-shipping-callback/getOrder.php index 22cc04cd..3bf423ef 100644 --- a/demo/paypal-checkout-shipping-callback/getOrder.php +++ b/demo/paypal-checkout-shipping-callback/getOrder.php @@ -54,6 +54,11 @@ $_SESSION['billing_country_code'] = isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : ''; $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; + + $captures = !empty($purchaseUnit['payments']['captures'][0]) ? $purchaseUnit['payments']['captures'][0] : []; + $_SESSION['paypal_transaction_id'] = isset($captures['id']) ? $captures['id'] : ''; + $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; + $shipping = isset( $purchaseUnit['shipping'] ) ? $purchaseUnit['shipping'] : []; $_SESSION['shipping_name'] = isset($shipping['name']['full_name']) ? $shipping['name']['full_name'] : ''; $_SESSION['shipping_street'] = isset($shipping['address']['address_line_1']) ? $shipping['address']['address_line_1'] : ''; diff --git a/demo/paypal-checkout-shipping-callback/index.php b/demo/paypal-checkout-shipping-callback/index.php index 10c45a86..fc50f02a 100644 --- a/demo/paypal-checkout-shipping-callback/index.php +++ b/demo/paypal-checkout-shipping-callback/index.php @@ -26,6 +26,7 @@ 'shipping' => 0, 'handling' => 0, 'tax' => 0, + 'shipping_callback_url' => $domain . '/demo/paypal-checkout-shipping-callback/shippingCallback.php', ); $_SESSION['shopping_cart']['grand_total'] = number_format($_SESSION['shopping_cart']['subtotal'] + $_SESSION['shopping_cart']['shipping'] + $_SESSION['shopping_cart']['handling'] + $_SESSION['shopping_cart']['tax'],2); ?> diff --git a/demo/paypal-checkout-shipping-callback/shipping-cb.js b/demo/paypal-checkout-shipping-callback/shipping-cb.js index 37504fd7..d6a3bd09 100644 --- a/demo/paypal-checkout-shipping-callback/shipping-cb.js +++ b/demo/paypal-checkout-shipping-callback/shipping-cb.js @@ -52,7 +52,7 @@ document.addEventListener("DOMContentLoaded", function () { brand_name: "AngellEYE", shipping_preference: "GET_FROM_FILE", order_update_callback_config: { - callback_url: 'shippingCallback.php', + callback_url: checkoutData.shipping_callback_url, callback_events: ['SHIPPING_ADDRESS'], } } From 8f2733c76da71b92c2dc12176e21f1e50f1d07e8 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 17 Mar 2026 10:39:31 +0530 Subject: [PATCH 145/146] Minor Shipping Callback Changes --- .../getOrder.php | 27 ++++++++++++++++++- .../index.php | 2 +- .../order-complete.php | 2 +- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/demo/paypal-checkout-shipping-callback/getOrder.php b/demo/paypal-checkout-shipping-callback/getOrder.php index 3bf423ef..8878e39f 100644 --- a/demo/paypal-checkout-shipping-callback/getOrder.php +++ b/demo/paypal-checkout-shipping-callback/getOrder.php @@ -53,7 +53,7 @@ $_SESSION['last_name'] = isset($PayPalResult['order']['payer']['name']['surname']) ? $PayPalResult['order']['payer']['name']['surname'] : ''; $_SESSION['billing_country_code'] = isset($PayPalResult['order']['payer']['address']['country_code']) ? $PayPalResult['order']['payer']['address']['country_code'] : ''; - $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; + $purchaseUnit = $PayPalResult['order']['purchase_units'][0]; $captures = !empty($purchaseUnit['payments']['captures'][0]) ? $purchaseUnit['payments']['captures'][0] : []; $_SESSION['paypal_transaction_id'] = isset($captures['id']) ? $captures['id'] : ''; @@ -67,6 +67,31 @@ $_SESSION['shipping_zip'] = isset($shipping['address']['postal_code']) ? $shipping['address']['postal_code'] : ''; $_SESSION['shipping_country_code'] = isset($shipping['address']['country_code']) ? $shipping['address']['country_code'] : ''; $_SESSION['shipping_country_name'] = 'United States'; + + /** + * At this point, we now have the buyer's shipping address available in our app. + * We could now run the data through a shipping calculator to retrieve rate + * information for this particular order. + * + * This would also be the time to calculate any sales tax you may need to + * add to the order, as well as handling fees. + */ + $breakdown = !empty($purchaseUnit['amount']['breakdown']) ? $purchaseUnit['amount']['breakdown'] : []; + $shipping = isset($breakdown['shipping']['value']) ? (float)$breakdown['shipping']['value'] : 0; + $handling = isset($breakdown['handling']['value']) ? (float)$breakdown['handling']['value'] : 0; + $tax = isset($breakdown['tax_total']['value']) ? (float)$breakdown['tax_total']['value'] : 0; + + // Store in session + $_SESSION['shopping_cart']['shipping'] = $shipping; + $_SESSION['shopping_cart']['handling'] = $handling; + $_SESSION['shopping_cart']['tax'] = $tax; + + // Recalculate grand total + $_SESSION['shopping_cart']['grand_total'] = number_format( + $_SESSION['shopping_cart']['subtotal'] + + $shipping + + $handling + + $tax, 2); /** * Now we will redirect the user to a final review diff --git a/demo/paypal-checkout-shipping-callback/index.php b/demo/paypal-checkout-shipping-callback/index.php index fc50f02a..98cd7a09 100644 --- a/demo/paypal-checkout-shipping-callback/index.php +++ b/demo/paypal-checkout-shipping-callback/index.php @@ -91,7 +91,7 @@

CartShopping Cart

-

Here we are using a basic shopping cart for display purposes, however, for this basic demo, all we are sending to PayPal is the order total without any line item details. We are assuming that we have not collected any billing or shipping information from the buyer yet because we'll be obtaining those details from PayPal after the user logs in and is returned back to the site.

+

Here we are using a basic shopping cart for display, sending only the order total to PayPal without line item details, and assuming billing and shipping information will be collected after the user logs in and returns from PayPal. Additionally, we invoke the shipping callback URL after order creation and before redirecting to PayPal to fetch the buyer’s shipping details, apply shipping, handling, and tax, and recalculate the final order amount accordingly.

Demo Credentials

Email: paypal-buyer@angelleye.com

diff --git a/demo/paypal-checkout-shipping-callback/order-complete.php b/demo/paypal-checkout-shipping-callback/order-complete.php index 1343da60..89cdbc3e 100644 --- a/demo/paypal-checkout-shipping-callback/order-complete.php +++ b/demo/paypal-checkout-shipping-callback/order-complete.php @@ -64,7 +64,7 @@

Payment Complete!

-

We have now reached the final thank you / receipt page and the payment has been processed! We have added the PayPal transaction ID to the Billing Information, which was provided in the DoExpressCheckoutPayment response.

+

We have now reached the final thank you/receipt page, and the payment has been successfully processed. The PayPal transaction ID has been added to the Billing Information as received in the getOrder response. Additionally, the order total was recalculated after applying shipping, handling, and tax via the shipping callback URL, and the updated amount was used for the final transaction.

From ca17bcf5b8d464bff927b0fdafee0365ab4521c9 Mon Sep 17 00:00:00 2001 From: meet-creedally Date: Tue, 17 Mar 2026 12:29:08 +0530 Subject: [PATCH 146/146] Multi Checkout Demo Completed --- .../basic-paypal.js | 188 ++++++++++++++++++ .../captureOrder.php | 60 ------ .../createOrder.php | 133 ------------- .../index.php | 11 +- .../order-complete.php | 5 + .../paylater.js | 177 ++++++++++++++++- 6 files changed, 367 insertions(+), 207 deletions(-) create mode 100644 demo/paypal-multiple-checkout-options/basic-paypal.js delete mode 100644 demo/paypal-multiple-checkout-options/captureOrder.php delete mode 100644 demo/paypal-multiple-checkout-options/createOrder.php diff --git a/demo/paypal-multiple-checkout-options/basic-paypal.js b/demo/paypal-multiple-checkout-options/basic-paypal.js new file mode 100644 index 00000000..e7e38040 --- /dev/null +++ b/demo/paypal-multiple-checkout-options/basic-paypal.js @@ -0,0 +1,188 @@ +document.addEventListener('DOMContentLoaded', function () { + // Initialize PayPal Pay Later Messages on load + initPayPal(); + + // CreateOrder and PayLater + let checkoutData = null; + const payLaterBtnContainer = document.getElementById("paypal-container"); + if ( payLaterBtnContainer !== undefined && payLaterBtnContainer !== null ) { + checkoutData = JSON.parse(payLaterBtnContainer.dataset.checkout); + } + + async function createOrder() { + try { + const items = checkoutData.checkout_options_items.map(item => ({ + name: item.name, + sku: item.id, + unit_amount: { + currency_code: "USD", + value: Number(item.price).toFixed(2) + }, + quantity: item.qty.toString(), + })); + + const orderPayload = { + intent: "CAPTURE", + payment_method: { + payer_selected: "PAYPAL" + }, + purchase_units: [ + { + reference_id: "ORDER-" + Date.now(), + invoice_id: "INV-" + Date.now(), + amount: { + currency_code: "USD", + value: Number(checkoutData.grand_total).toFixed(2), + breakdown: { + item_total: { + currency_code: "USD", + value: Number(checkoutData.subtotal).toFixed(2), + }, + shipping: { + currency_code: "USD", + value: Number(checkoutData.shipping).toFixed(2), + }, + handling: { + currency_code: "USD", + value: Number(checkoutData.handling).toFixed(2), + }, + tax_total: { + currency_code: "USD", + value: Number(checkoutData.tax).toFixed(2), + } + }, + }, + items: items, + }, + ], + payment_source: { + paypal: { + experience_context: { + brand_name: "AngellEYE", + shipping_preference: "GET_FROM_FILE", + user_action: "PAY_NOW" + } + } + } + }; + + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(orderPayload) + }) + + const data = await response.json(); + if (!data.order_id) { + showPaypalError("Unable to create PayPal order."); + return; + } + + return { orderId: data?.order_id }; + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + function showPaypalError(message) { + const payPalContainer = document.getElementById('paypal-container'); + if( payPalContainer !== undefined && payPalContainer !== null ) { + const errorContainer = payPalContainer.querySelector('#paypalError'); + if( errorContainer !== undefined && errorContainer !== null ) { + errorContainer.style.display = "block"; + errorContainer.innerHTML = message; + } + } + } + + async function captureOrder(data) { + try { + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_capture_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id: data.orderId }), + }); + + const captureResult = await response.json(); + + if (captureResult.status === "COMPLETED") { + window.location.href = `getOrder.php?payment_mode=paypal&order_id=${data.orderId}`; + } else { + throw new Error("Payment capture failed."); + } + + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + const paymentSessionOptions = { + async onApprove(data) { + try { + const orderData = await captureOrder({ + orderId: data.orderId, + }); + } catch (error) { + showPaypalError(error.message); + throw error; + } + }, + onCancel() { + location.reload(); + }, + onError(error) { + showPaypalError(error.message); + }, + }; + + /** + * PAYPAL V6 SDK INITIALIZATION + * Fetches a client token and sets up the financing messages. + */ + async function initPayPal() { + try { + const res = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_client_token'); + const { token } = await res.json(); + + const sdkInstance = await paypal.createInstance({ + clientToken: token, + components: ["paypal-payments"], + pageType: 'checkout', + }); + + const paymentMethods = await sdkInstance.findEligibleMethods({ + currencyCode: "USD", + }); + + if (paymentMethods.isEligible("paypal")) { + setUpPayLaterButton(sdkInstance); + } + } catch (error) { + console.error("PayPal Message Init Error:", error); + } + } + + // Set up standard PayPal button + async function setUpPayLaterButton(sdkInstance, paymentMethods) { + const paypalPaymentSession = sdkInstance.createPayPalOneTimePaymentSession( + paymentSessionOptions, + ); + + const payPalButton = document.querySelector("paypal-button"); + if ( !payPalButton ) return; + + payPalButton.removeAttribute("hidden"); + payPalButton.addEventListener("click", async () => { + try { + await paypalPaymentSession.start( + { presentationMode: "auto" }, + createOrder(), + ); + } catch (error) { + showPaypalError(`PayPal payment start error: ${error}`) + } + }); + } +}); \ No newline at end of file diff --git a/demo/paypal-multiple-checkout-options/captureOrder.php b/demo/paypal-multiple-checkout-options/captureOrder.php deleted file mode 100644 index b407e378..00000000 --- a/demo/paypal-multiple-checkout-options/captureOrder.php +++ /dev/null @@ -1,60 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$paymentMode = isset($_GET['payment_mode']) ? $_GET['payment_mode'] : ''; - -/** - * Here we are making the call to the DoExpressCheckoutPayment function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ -$PayPalResult = $PayPal->captureOrder($_SESSION['paypal_token']); - -/** - * Now we'll setup the request params for the final call in the Express Checkout flow. - * This is very similar to SetExpressCheckout except that now we can include values - * for the shipping, handling, and tax amounts, as well as the buyer's name and - * shipping address that we obtained in the GetExpressCheckoutDetails step. - * - * If this information is not included in this final call, it will not be - * available in PayPal's transaction details data. - * - * Once again, the template for DoExpressCheckoutPayment provides - * many more params that are available, but we've stripped everything - * we are not using in this basic demo out. - */ -if( $PayPalResult['success'] ) { - $_SESSION['paypal_transaction_id'] = isset( $PayPalResult['capture_id'] ) ? $PayPalResult['capture_id'] : ''; - - $captures = ( $PayPalResult['purchase_units'][0]['payments']['captures'][0] ) ? $PayPalResult['purchase_units'][0]['payments']['captures'][0] : []; - $_SESSION['paypal_fee'] = isset( $captures['seller_receivable_breakdown']['paypal_fee']['value'] ) ? $captures['seller_receivable_breakdown']['paypal_fee']['value'] : 0.00; - - header('Location: getOrder.php?payment_mode='. $paymentMode .'&order_id=' . $_SESSION['paypal_token']); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-multiple-checkout-options/createOrder.php b/demo/paypal-multiple-checkout-options/createOrder.php deleted file mode 100644 index d941d1ee..00000000 --- a/demo/paypal-multiple-checkout-options/createOrder.php +++ /dev/null @@ -1,133 +0,0 @@ - $sandbox, - 'PayPalAPIMode' => $api_mode, - 'PayPalAPIUpgrade' => $api_upgrade, - 'ClientID' => $rest_client_id, - 'ClientSecret' => $rest_client_secret, - 'PrintHeaders' => $print_headers, - 'LogResults' => $log_results, - 'LogPath' => $log_path, -); -$PayPal = angelleye\PayPal\PayPal::init($PayPalConfig); - -$paymentMode = isset($_GET['payment_mode']) ? $_GET['payment_mode'] : ''; - -// Map items from session -$purchase_items = []; -foreach ($_SESSION['checkout_options_items'] as $item) { - $purchase_items[] = [ - "name" => $item['name'], - "sku" => $item['id'], - "unit_amount" => [ - "currency_code" => "USD", - "value" => number_format($item['price'], 2, '.', '') - ], - "quantity" => (string)$item['qty'] - ]; -} - -// Build the Base Payload -$payload = [ - "intent" => "CAPTURE", - "purchase_units" => [[ - "items" => $purchase_items, - "amount" => [ - "currency_code" => "USD", - "value" => $_SESSION['shopping_cart']['grand_total'], - "breakdown" => [ - "item_total" => [ - "currency_code" => "USD", - "value" => number_format($_SESSION['shopping_cart']['subtotal'], 2, '.', '') - ], - "shipping" => [ - "currency_code" => "USD", - "value" => number_format($_SESSION['shopping_cart']['shipping'], 2, '.', '') - ], - "handling" => [ - "currency_code" => "USD", - "value" => number_format($_SESSION['shopping_cart']['handling'], 2, '.', '') - ], - "tax_total" => [ - "currency_code" => "USD", - "value" => number_format($_SESSION['shopping_cart']['tax'], 2, '.', '') - ] - ] - ] - ]], - "payment_source" => [ - "paypal" => [ - "experience_context" => [ - "brand_name" => "Angell EYE", - "shipping_preference" => "GET_FROM_FILE", - "user_action" => "PAY_NOW", - "return_url" => $domain . "demo/paypal-multiple-checkout-options/captureOrder.php?payment_mode=" . $paymentMode, - "cancel_url" => $domain . "demo/paypal-multiple-checkout-options/", - ], - ] - ] -]; - -/** - * Here we are making the call to the createOrder function in the library, - * and we're passing in our $PayPalRequestData that we just set above. - */ -$PayPalResult = $PayPal->createOrder($payload); - -/** - * Based on the selected API mode, extract the appropriate redirect URL - * and order identifier from the createOrder response. - * - * - For REST mode (when API upgrade is disabled), PayPal returns an - * `approval_url` for redirection and an `order_id` to track the transaction. - * - For Classic mode (or when API upgrade is enabled), PayPal returns a - * `REDIRECTURL` for redirection and a `TOKEN` that represents the checkout session. - * - * These values are normalized into $redirect_url and $orderId so the - * remaining flow can work consistently regardless of API mode. - */ -$redirect_url = ''; -if( !$api_upgrade ) { - $redirect_url = $PayPalResult['approval_url']; -} else { - $redirect_url = $PayPalResult['REDIRECTURL']; -} - -$orderId = ''; -if( !$api_upgrade ) { - $orderId = $PayPalResult['order_id']; -} else { - $orderId = $PayPalResult['TOKEN']; -} - -/** - * Now we'll check for any errors returned by PayPal, and if we get an error, - * we'll save the error details to a session and redirect the user to an - * error page to display it accordingly. - * - * If all goes well, we save our token in a session variable so that it's - * readily available for us later, and then redirect the user to PayPal - * using the REDIRECTURL returned by the SetExpressCheckout() function. - */ -if( !empty($redirect_url) ) { - $_SESSION['paypal_token'] = $orderId; - header('Location: ' . $redirect_url); -} else { - $_SESSION['paypal_errors'] = $PayPalResult['ERRORS']; - header('Location: ../error.php'); -} \ No newline at end of file diff --git a/demo/paypal-multiple-checkout-options/index.php b/demo/paypal-multiple-checkout-options/index.php index 68c52b75..1dd911c2 100644 --- a/demo/paypal-multiple-checkout-options/index.php +++ b/demo/paypal-multiple-checkout-options/index.php @@ -112,6 +112,7 @@ ?> + @@ -221,7 +222,10 @@
- renderPayPalButton(); ?> +
'> +
+ +
'> @@ -232,9 +236,10 @@
'>
- +
OR
diff --git a/demo/paypal-multiple-checkout-options/order-complete.php b/demo/paypal-multiple-checkout-options/order-complete.php index 850a1327..088b3a75 100644 --- a/demo/paypal-multiple-checkout-options/order-complete.php +++ b/demo/paypal-multiple-checkout-options/order-complete.php @@ -1,5 +1,10 @@ diff --git a/demo/paypal-multiple-checkout-options/paylater.js b/demo/paypal-multiple-checkout-options/paylater.js index faf89b2d..8437338e 100644 --- a/demo/paypal-multiple-checkout-options/paylater.js +++ b/demo/paypal-multiple-checkout-options/paylater.js @@ -2,6 +2,141 @@ document.addEventListener('DOMContentLoaded', function () { // Initialize PayPal Pay Later Messages on load initPayPalMessages(); + // CreateOrder and PayLater + let checkoutData = null; + const payLaterBtnContainer = document.getElementById("paylater-container"); + if ( payLaterBtnContainer !== undefined && payLaterBtnContainer !== null ) { + checkoutData = JSON.parse(payLaterBtnContainer.dataset.checkout); + } + + async function createOrder() { + try { + const items = checkoutData.checkout_options_items.map(item => ({ + name: item.name, + sku: item.id, + unit_amount: { + currency_code: "USD", + value: Number(item.price).toFixed(2) + }, + quantity: item.qty.toString(), + })); + + const orderPayload = { + intent: "CAPTURE", + payment_method: { + payer_selected: "PAYPAL" + }, + purchase_units: [ + { + reference_id: "ORDER-" + Date.now(), + invoice_id: "INV-" + Date.now(), + amount: { + currency_code: "USD", + value: Number(checkoutData.grand_total).toFixed(2), + breakdown: { + item_total: { + currency_code: "USD", + value: Number(checkoutData.subtotal).toFixed(2), + }, + shipping: { + currency_code: "USD", + value: Number(checkoutData.shipping).toFixed(2), + }, + handling: { + currency_code: "USD", + value: Number(checkoutData.handling).toFixed(2), + }, + tax_total: { + currency_code: "USD", + value: Number(checkoutData.tax).toFixed(2), + } + }, + }, + items: items, + }, + ], + payment_source: { + paypal: { + experience_context: { + brand_name: "AngellEYE", + shipping_preference: "GET_FROM_FILE", + user_action: "PAY_NOW" + } + } + } + }; + + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_create_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(orderPayload) + }) + + const data = await response.json(); + if (!data.order_id) { + showPaypalError("Unable to create PayPal order."); + return; + } + + return { orderId: data?.order_id }; + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + function showPaypalError(message) { + const paylaterContainer = document.getElementById('paylater-container'); + if( paylaterContainer !== undefined && paylaterContainer !== null ) { + const errorContainer = paylaterContainer.querySelector('#paypalError'); + if( errorContainer !== undefined && errorContainer !== null ) { + errorContainer.style.display = "block"; + errorContainer.innerHTML = message; + } + } + } + + async function captureOrder(data) { + try { + const response = await fetch('../../src/angelleye/PayPal/api/paypal-api.php?action=ae_capture_order', { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ id: data.orderId }), + }); + + const captureResult = await response.json(); + + if (captureResult.status === "COMPLETED") { + window.location.href = `getOrder.php?payment_mode=paylater&order_id=${data.orderId}`; + } else { + throw new Error("Payment capture failed."); + } + + } catch (error) { + showPaypalError(error.message); + throw error; + } + } + + const paymentSessionOptions = { + async onApprove(data) { + try { + const orderData = await captureOrder({ + orderId: data.orderId, + }); + } catch (error) { + showPaypalError(error.message); + throw error; + } + }, + onCancel() { + location.reload(); + }, + onError(error) { + showPaypalError(error.message); + }, + }; + /** * PAYPAL V6 SDK INITIALIZATION * Fetches a client token and sets up the financing messages. @@ -22,20 +157,40 @@ document.addEventListener('DOMContentLoaded', function () { }); if (paymentMethods.isEligible("paylater")) { - // Initialize PayLater Messaging - const messagesInstance = sdkInstance.createPayPalMessages(); - - const payLaterPaymentMethodDetails = paymentMethods.getDetails("paylater"); - const { productCode, countryCode } = payLaterPaymentMethodDetails; - const payLaterButton = document.querySelector("paypal-pay-later-button"); - - // Configure button with Pay Later specific details - payLaterButton.productCode = productCode; - payLaterButton.countryCode = countryCode; - payLaterButton.removeAttribute("hidden"); + setUpPayLaterButton(sdkInstance, paymentMethods); } } catch (error) { console.error("PayPal Message Init Error:", error); } } + + // Set up standard PayPal button + async function setUpPayLaterButton(sdkInstance, paymentMethods) { + const payLaterPaymentMethodDetails = paymentMethods.getDetails("paylater"); + const { productCode, countryCode } = payLaterPaymentMethodDetails; + + // Initialize PayLater Messaging + const messagesInstance = sdkInstance.createPayPalMessages(); + + const paypalPaymentSession = sdkInstance.createPayLaterOneTimePaymentSession( + paymentSessionOptions, + ); + + const payLaterButton = document.querySelector("paypal-pay-later-button"); + if ( !payLaterButton ) return; + + payLaterButton.productCode = productCode; + payLaterButton.countryCode = countryCode; + payLaterButton.removeAttribute("hidden"); + payLaterButton.addEventListener("click", async () => { + try { + await paypalPaymentSession.start( + { presentationMode: "auto" }, + createOrder(), + ); + } catch (error) { + showPaypalError(`PayPal payment start error: ${error}`) + } + }); + } }); \ No newline at end of file