From 5207c2d7c8da1779b800ee1ac0f9bc6725a2a6c9 Mon Sep 17 00:00:00 2001 From: vikram chand Date: Mon, 18 Jul 2022 21:45:56 +0530 Subject: [PATCH 01/26] Updated: stripe payment --- Libraries/VaahStripe.md | 92 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 2 deletions(-) diff --git a/Libraries/VaahStripe.md b/Libraries/VaahStripe.md index 2641a17..5f53723 100644 --- a/Libraries/VaahStripe.md +++ b/Libraries/VaahStripe.md @@ -76,12 +76,100 @@ Reference url: https://stripe.com/docs/api 'state' => 'xxxxxx' // optional ]; - $return_url // URL to redirect your customer back to after they authenticate or cancel their payment + $return_url = http://localhost/vaahcms/public/ // URL to redirect your customer back to after they authenticate or cancel their payment \VaahStripe::pay($customer, $card, $package, $address, $return_url); ``` +Response + +``` +{ + "status": "success", + "data": { + "id": "pi_1LMvsxxxxxxxxxxxxxxxxxx", + "object": "payment_intent", + "allowed_source_types": [ + "card" + ], + "amount": 200, + "amount_capturable": 0, + "amount_details": { + "tip": [] + }, + "amount_received": 0, + "application": null, + "application_fee_amount": null, + "automatic_payment_methods": null, + "canceled_at": null, + "cancellation_reason": null, + "capture_method": "automatic", + "charges": { + "object": "list", + "data": [], + "has_more": false, + "total_count": 0, + "url": "/v1/charges?payment_intent=pi_1LMvsxxxxxxxxxxxxxxxxxx" + }, + "client_secret": "pi_1LMvsxxxxxxxxxxxxxxxxxx_secret_8RZiIyhUEGDqfyLOgSUEAEhXN", + "confirmation_method": "automatic", + "created": 1658158118, + "currency": "usd", + "customer": "cus_M564xxxxxxx", + "description": "testing", + "invoice": null, + "last_payment_error": null, + "livemode": false, + "metadata": [], + "next_action": { + "redirect_to_url": { + "return_url": "http://localhost/vikram/vaahcms-dev-env/public", + "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to open 3d Secure / OTP Page + acct_1G43A8GBqaITyEUt&payment_intent=pi_1LMvsxxxxxxxxxxxxxxxxxx& + payment_intent_client_secret=pi_1LMvsxxxxxxxxxxxxxxxxxx_secret_8RZiIyhUEGDqfyLOgSUEAEhXN& + publishable_key=pk_test_xaKKES0OlRzwNj6mCRBbjfc200upEjyqmB&source=src_1LMvsEGBqaITyEUtehquCgzp" + }, + "type": "redirect_to_url" + }, + "next_source_action": { + "type": "authorize_with_url", + "authorize_with_url": { + "return_url": "http://localhost/vikram/vaahcms-dev-env/public", + "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to open 3d Secure / OTP Page + acct_1G43A8GBqaITyEUt&payment_intent=pi_1LMvsxxxxxxxxxxxxxxxxxx& + payment_intent_client_secret=pi_1LMvsxxxxxxxxxxxxxxxxxx_secret_8RZiIyhUEGDqfyLOgSUEAEhXN& + publishable_key=pk_test_xaKKES0OlRzwNj6mCRBbjfc200upEjyqmB&source=src_1LMvsEGBqaITyEUtehquCgzp" + } + }, + "on_behalf_of": null, + "payment_method": "pm_1LMvsxxxxxxxxxxxxxxxxxx", + "payment_method_options": { + "card": { + "installments": null, + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "processing": null, + "receipt_email": null, + "review": null, + "setup_future_usage": null, + "shipping": null, + "source": null, + "statement_descriptor": null, + "statement_descriptor_suffix": null, + "status": "requires_source_action", + "transfer_data": null, + "transfer_group": null + } +} +``` + - Stripe Subscription ```php @@ -108,7 +196,7 @@ Reference url: https://stripe.com/docs/api $price_id // Price define the unit cost, currency, and (optional) billing cycle for Subcription - $return_url // URL to redirect your customer back to after they authenticate or cancel their payment + $return_url = http://localhost/vaahcms/public/ // URL to redirect your customer back to after they authenticate or cancel their payment \VaahStripe::subscription($customer, $card, $address, $price_id, $return_url); From 27f7a5c6a7423553f632ba277421323cabb4ceaf Mon Sep 17 00:00:00 2001 From: vikram chand Date: Mon, 18 Jul 2022 22:03:34 +0530 Subject: [PATCH 02/26] Updated: stripe subscription readme --- Libraries/VaahStripe.md | 99 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 4 deletions(-) diff --git a/Libraries/VaahStripe.md b/Libraries/VaahStripe.md index 5f53723..9c1f47a 100644 --- a/Libraries/VaahStripe.md +++ b/Libraries/VaahStripe.md @@ -88,7 +88,7 @@ Response { "status": "success", "data": { - "id": "pi_1LMvsxxxxxxxxxxxxxxxxxx", + "id": "pi_1LMvsxxxxxxxxxxxxxxxxxx", // Payment Intent ID "object": "payment_intent", "allowed_source_types": [ "card" @@ -125,7 +125,7 @@ Response "next_action": { "redirect_to_url": { "return_url": "http://localhost/vikram/vaahcms-dev-env/public", - "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to open 3d Secure / OTP Page + "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to complete your 3D secure Payment or open OTP Page acct_1G43A8GBqaITyEUt&payment_intent=pi_1LMvsxxxxxxxxxxxxxxxxxx& payment_intent_client_secret=pi_1LMvsxxxxxxxxxxxxxxxxxx_secret_8RZiIyhUEGDqfyLOgSUEAEhXN& publishable_key=pk_test_xaKKES0OlRzwNj6mCRBbjfc200upEjyqmB&source=src_1LMvsEGBqaITyEUtehquCgzp" @@ -136,7 +136,7 @@ Response "type": "authorize_with_url", "authorize_with_url": { "return_url": "http://localhost/vikram/vaahcms-dev-env/public", - "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to open 3d Secure / OTP Page + "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to complete your 3D secure Payment or open OTP Page acct_1G43A8GBqaITyEUt&payment_intent=pi_1LMvsxxxxxxxxxxxxxxxxxx& payment_intent_client_secret=pi_1LMvsxxxxxxxxxxxxxxxxxx_secret_8RZiIyhUEGDqfyLOgSUEAEhXN& publishable_key=pk_test_xaKKES0OlRzwNj6mCRBbjfc200upEjyqmB&source=src_1LMvsEGBqaITyEUtehquCgzp" @@ -194,7 +194,8 @@ Response 'state' => 'xxxxxx' // optional ]; - $price_id // Price define the unit cost, currency, and (optional) billing cycle for Subcription + $price_id You can generate Price ID from createPrice Method of Vaah Stripe // Price define the unit cost, currency, and (optional) billing cycle for Subcription + or You can create directly from Stripe Dashboard by visit https://dashboard.stripe.com/test/products/create $return_url = http://localhost/vaahcms/public/ // URL to redirect your customer back to after they authenticate or cancel their payment @@ -202,6 +203,94 @@ Response ``` +Response + +``` +{ + "status": "success", + "data": { + "id": "pi_1LMwxxxxxxxxxxxxxxxxxxxx", + "object": "payment_intent", + "allowed_source_types": [ + "card" + ], + "amount": 79900, + "amount_capturable": 0, + "amount_details": { + "tip": [] + }, + "amount_received": 0, + "application": null, + "application_fee_amount": null, + "automatic_payment_methods": null, + "canceled_at": null, + "cancellation_reason": null, + "capture_method": "automatic", + "charges": { + "object": "list", + "data": [], + "has_more": false, + "total_count": 0, + "url": "/v1/charges?payment_intent=pi_1LMwxxxxxxxxxxxxxxxxxxxx" + }, + "client_secret": "pi_1LMwxxxxxxxxxxxxxxxxxxxx_secret_usv8FrEvzU0CuWEyRjmUKlmjD", + "confirmation_method": "automatic", + "created": 1658161603, + "currency": "usd", + "customer": "cus_M570qAPnoC6xl1", + "description": "Subscription creation", + "invoice": "in_1LMwmxxxxxxxxxxxxxxxxxxx", + "last_payment_error": null, + "livemode": false, + "metadata": [], + "next_action": { + "redirect_to_url": { + "return_url": "http://localhost/vikram/vaahcms-dev-env/public", + "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to complete your 3D secure Payment or open OTP Page + acct_1G43A8GBqaITyEUt&payment_intent=pi_1LMwxxxxxxxxxxxxxxxxxxxx& + payment_intent_client_secret=pi_1LMwxxxxxxxxxxxxxxxxxxxx_secret_usv8FrEvzU0CuWEyRjmUKlmjD& + publishable_key=pk_test_xaKKES0OlRzwNj6mCRBbjfc200upEjyqmB&source=src_1LMwmQGBqaITyEUtQsNKeDZn" + }, + "type": "redirect_to_url" + }, + "next_source_action": { + "type": "authorize_with_url", + "authorize_with_url": { + "return_url": "http://localhost/vikram/vaahcms-dev-env/public", + "url": "https://hooks.stripe.com/3d_secure_2/hosted?merchant= // Url to complete your 3D secure Payment or open OTP Page + acct_1G43A8GBqaITyEUt&payment_intent=pi_1LMwxxxxxxxxxxxxxxxxxxxx& + payment_intent_client_secret=pi_1LMwxxxxxxxxxxxxxxxxxxxx_secret_usv8FrEvzU0CuWEyRjmUKlmjD& + publishable_key=pk_test_xaKKES0OlRzwNj6mCRBbjfc200upEjyqmB&source=src_1LMwmQGBqaITyEUtQsNKeDZn" + } + }, + "on_behalf_of": null, + "payment_method": null, + "payment_method_options": { + "card": { + "installments": null, + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "processing": null, + "receipt_email": null, + "review": null, + "setup_future_usage": "off_session", + "shipping": null, + "source": "card_1LMxxxxxxxxxxxxxxxxx", + "statement_descriptor": null, + "statement_descriptor_suffix": null, + "status": "requires_source_action", + "transfer_data": null, + "transfer_group": null + } +} +``` + - Create Product ```php @@ -217,6 +306,8 @@ Response - Create Price ```php + // You need to have Product id to create Price. + $request => [ 'product_id' => 'xxxxxx', 'currency' => 'usd', From 3a733b12a3d84bb046fc77a7600b45373632a11c Mon Sep 17 00:00:00 2001 From: vikram chand Date: Mon, 18 Jul 2022 22:24:18 +0530 Subject: [PATCH 03/26] Updated: product and price read --- Libraries/VaahStripe.md | 156 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 152 insertions(+), 4 deletions(-) diff --git a/Libraries/VaahStripe.md b/Libraries/VaahStripe.md index 9c1f47a..e5f2489 100644 --- a/Libraries/VaahStripe.md +++ b/Libraries/VaahStripe.md @@ -82,7 +82,7 @@ Reference url: https://stripe.com/docs/api ``` -Response +Success Response ``` { @@ -203,13 +203,13 @@ Response ``` -Response +Success Response ``` { "status": "success", "data": { - "id": "pi_1LMwxxxxxxxxxxxxxxxxxxxx", + "id": "pi_1LMwxxxxxxxxxxxxxxxxxxxx", // Payment Intent ID "object": "payment_intent", "allowed_source_types": [ "card" @@ -303,6 +303,42 @@ Response ``` +Success Response + +``` +{ + "status": "success", + "data": { + "id": "prod_M57xxxxxxxxxxx", // Product Id + "object": "product", + "active": true, + "attributes": [], + "created": 1658162168, + "default_price": null, + "description": "Testing Product", + "images": [], + "livemode": false, + "metadata": [], + "name": "Vikram", + "package_dimensions": null, + "shippable": null, + "skus": { + "object": "list", + "data": [], + "has_more": false, + "total_count": 0, + "url": "/v1/skus?product=prod_M57xxxxxxxxxxx&active=true" + }, + "statement_descriptor": null, + "tax_code": null, + "type": "service", + "unit_label": null, + "updated": 1658162168, + "url": null + } +} +``` + - Create Price ```php @@ -312,7 +348,9 @@ Response 'product_id' => 'xxxxxx', 'currency' => 'usd', 'amount' => '01', - 'interval' => '01' + 'recurring' => [ + 'interval' => 'month' // month, year, week, or day + ] ]; @@ -320,16 +358,91 @@ Response ``` +Success Response + +``` +{ + "status": "success", + "data": { + "id": "price_1LMxxxxxxxxxxxxxxxx", // Price id + "object": "price", + "active": true, + "billing_scheme": "per_unit", + "created": 1658162583, + "currency": "usd", + "custom_unit_amount": null, + "livemode": false, + "lookup_key": null, + "metadata": [], + "nickname": null, + "product": "prod_M579xxxxxxxx", // Product id + "recurring": { + "aggregate_usage": null, + "interval": "month", + "interval_count": 1, + "trial_period_days": null, + "usage_type": "licensed" + }, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "recurring", + "unit_amount": 20, + "unit_amount_decimal": "20" + } +} +``` + - Find Product ```php + + $name // Product Name \VaahStripe::findProductByName($name); ``` +Success Response + +``` +{ + "status": "success", + "data": { + "id": "prod_K1xxxxxxxx", + "object": "product", + "active": true, + "attributes": [], + "caption": null, + "created": 1628777285, + "deactivate_on": [], + "default_price": null, + "description": "WP-Maintenance-Premium-Monthly", + "images": [], + "livemode": false, + "metadata": [], + "name": "WP-Maintenance-Standard-Monthly", + "package_dimensions": null, + "shippable": true, + "skus": { + "object": "list", + "data": [], + "has_more": false, + "total_count": 0, + "url": "/v1/skus?product=prod_K1xxxxxxxxx&active=true" + }, + "tax_code": null, + "type": "good", + "updated": 1628777285, + "url": null + } +} +``` + - Find Price ```php + // You need to have Product id to create Price. + $product_id $value //optional @@ -339,3 +452,38 @@ Response \VaahStripe::getProductPrice($product_id, $value, $by); ``` + +Success Response + +``` +{ + "status": "success", + "data": { + "id": "price_1LMx2xxxxxxxxxxxxxxx", + "object": "price", + "active": true, + "billing_scheme": "per_unit", + "created": 1658162583, + "currency": "usd", + "custom_unit_amount": null, + "livemode": false, + "lookup_key": null, + "metadata": [], + "nickname": null, + "product": "prod_M57xxxxxxxxxxxx", + "recurring": { + "aggregate_usage": null, + "interval": "month", + "interval_count": 1, + "trial_period_days": null, + "usage_type": "licensed" + }, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "recurring", + "unit_amount": 20, + "unit_amount_decimal": "20" + } +} +``` From 0620762a88b154e8708e1f0759491710af1edfd2 Mon Sep 17 00:00:00 2001 From: Vikram Date: Mon, 28 Nov 2022 11:46:26 +0530 Subject: [PATCH 04/26] Added: vaahpaypal class file --- Libraries/VaahPayPal.php | 888 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 888 insertions(+) create mode 100644 Libraries/VaahPayPal.php diff --git a/Libraries/VaahPayPal.php b/Libraries/VaahPayPal.php new file mode 100644 index 0000000..90d7c98 --- /dev/null +++ b/Libraries/VaahPayPal.php @@ -0,0 +1,888 @@ + 20.00, + 'tax' => 10.00, + 'success_url' => 'http://localhost/vikram/morapp/public', + //route for redirection after payment success. + 'failed_url' => 'http://localhost/vikram/morapp/public', + //route for redirection after payment failure. + 'item_name' => "Item one", + 'item_sku' => "item-one", + 'item_desc' => "This is the product", + 'currency' => "USD", + 'item_quantity' => 5, + 'invoice_number' => uniqid(), + 'payment_frequency' => 'Month', + // can be `WEEK`, `DAY`, `YEAR`, `MONTH`. + 'payment_interval' => 1, + // in how many months, days, or week you to execute the same payment. + 'cycles' => 12, + // in how many months, days, or week you to execute the same payment. 0 if plan type is infinite + 'plan_type' => 12, + // Allowed values: `FIXED`, `INFINITE` infinite is for subscription or fixed for EMIs. + ]; + + $rules = array( + 'price' => 'required|numeric', +// 'tax' => 'required|numeric', + 'success_url' => 'required', + 'failed_url' => 'required', + 'item_name' => 'required', + 'item_sku' => 'required', + 'currency' => 'required', + 'item_quantity' => 'required|integer', + 'invoice_number' => 'required', + ); + $messages = [ + 'price.required' => 'Price is required.', + 'item_quantity.required' => 'Item quantity is required.', + 'tax.required' => 'Tax is required.', + 'price.numeric' => 'Price should be in Numbers.', + 'item_quantity.numeric' => 'Item Quantity should be in Numbers.', + 'tax.numeric' => 'Tax should be in Numbers.', + 'success_url.required' => 'Success url is required.', + 'failed_url.required' => 'Failure url is required.', + 'item_name.required' => 'Item name is required.', + 'item_sku.required' => 'Item sku is required.', + 'currency.required' => 'Currency is required.', + 'invoice_number.required' => 'Invoice number is required.', + ]; + $validator = \Validator::make( $inputs, $rules, $messages ); + if ( $validator->fails() ) { + + $errors = $validator->errors(); + $response['status'] = 'failed'; + $response['errors'] = $errors; + + return $response; + } + $response = []; + $address = null; + if ( $shippingAddress && is_array( $shippingAddress ) ) { + $res = $this->setShippingAddress( $shippingAddress ); + if ( $res['status'] === 'failed' ) { + return $res; + } + if ( $res['status'] === 'success' ) { + $address = $res['data']; + } + } + + $tax = 0; + + if (isset($inputs['tax']) && $inputs['tax']>0){ + if (!is_numeric($inputs['tax'])){ + $response['status'] = 'failed'; + $response['errors'][] = 'Tax should be in numbers'; + + return $response; + } + $tax = $inputs['tax']; + } + + $payer = new Payer(); + $payer->setPaymentMethod( "paypal" ); + $item = new Item(); + $item->setName( $inputs['item_name'] ) + ->setCurrency( $inputs['currency'] ) + ->setSku( $inputs['item_sku'] ) + ->setQuantity( $inputs['item_quantity'] ) + ->setPrice( $inputs['price'] ); + $details = new \PayPal\Api\Details(); + $details->setTax( $tax )->setSubtotal( $inputs['price'] ); + $itemList = new ItemList(); + $itemList->setItems( [ $item ] ); + if ( $address ) { + $itemList->setShippingAddress( $address ); + } + $_amount = $inputs['price'] + $tax; + //Payment Amount + $amount = new Amount(); + $amount->setCurrency( $inputs['currency'] ) + // the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping). + ->setTotal( ( $_amount ) )->setDetails( $details ); + // ### Transaction + // A transaction defines the contract of a + // payment - what is the payment for and who + // is fulfilling it. Transaction is created with + // a `Payee` and `Amount` types + //die; + $transaction = new Transaction(); + $transaction->setAmount( $amount ) + ->setItemList( $itemList ) +// ->setDescription("Assignable.io Cart ID: ".$cart->uid) + ->setInvoiceNumber( $inputs['invoice_number'] ); + // ### Payment + // A Payment Resource; create one using + // the above types and intent as 'sale' + //die; + $redirectUrls = new RedirectUrls(); + $redirectUrls->setReturnUrl( $inputs['success_url'] ) + ->setCancelUrl( $inputs['failed_url'] ); + $payment = new Payment(); + $payment->setIntent( "sale" ) + ->setPayer( $payer ) + ->setRedirectUrls( $redirectUrls ) + ->setTransactions( [ $transaction ] ); + try { + // ### Create Payment + // Create a payment by posting to the APIService + // using a valid ApiContext + // The return object contains the status; + $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), env( 'PAYPAL_CLIENT_SECRET', '' ) ); + $payment->create( $apiContext ); + $approved_url = $payment->getApprovalLink(); + $approved_url = parse_url( $approved_url ); + parse_str( $approved_url['query'], $approved_query_params ); + } catch ( \Exception $ex ) { + + $response['status'] = 'failed'; + $response['errors'][] = $ex->getMessage(); + + return $response; + } + $response['status'] = 'success'; + $response['data']['redirect_url'] = $payment->getApprovalLink(); + $response['messages'][] = 'Redirecting you to PayPal'; + + return $response; + } public function payPalSubscription( $inputs ) { + + $rules = array( + 'price' => 'required|numeric', +// 'tax' => 'required|numeric', + 'success_url' => 'required', + 'plan_type' => 'required', + 'failed_url' => 'required', + 'item_name' => 'required', + 'item_sku' => 'required', + 'item_desc' => 'required', + 'currency' => 'required', + 'item_quantity' => 'required|integer', + 'invoice_number' => 'required', + 'payment_frequency' => 'required', + 'payment_interval' => 'required|integer', + 'payment_cycles' => 'required|integer', + ); + $messages = [ + 'price.required' => 'Price is required.', + 'item_quantity.required' => 'Item quantity is required.', + 'tax.required' => 'Tax is required.', + 'price.numeric' => 'Price should be in Numbers.', + 'item_quantity.numeric' => 'Item Quantity should be in Numbers.', + 'tax.numeric' => 'Tax should be in Numbers.', + 'success_url.required' => 'Success url is required.', + 'failed_url.required' => 'Failure url is required.', + 'item_name.required' => 'Item name is required.', + 'item_desc.required' => 'Item description is required.', + 'item_sku.required' => 'Item sku is required.', + 'currency.required' => 'Currency is required.', + 'invoice_number.required' => 'Invoice number is required.', + 'plan_type.required' => 'Plan Type is required this should be infinite or fixed.', + 'payment_interval.required' => 'Payment interval is required.', + 'payment_frequency.required' => 'Payment frequency is required.', + 'payment_cycles.integer' => 'Payment cycles should be in integer.', + 'payment_interval.integer' => 'Payment interval should be in integer.', + 'payment_cycles.required' => 'Payment Cycle is required.', + ]; + $validator = \Validator::make( $inputs, $rules, $messages ); + if ( $validator->fails() ) { + + $errors = $validator->errors(); + $response['status'] = 'failed'; + $response['errors'] = $errors; + + return $response; + } + $plan = new Plan(); + $plan->setName( $inputs['item_name'] ) + ->setDescription( $inputs['item_desc'] ) + ->setType( $inputs['plan_type'] ); //infinite or fixed + // Set billing plan definitions + $paymentDefinition = new PaymentDefinition(); + $paymentDefinition->setName( 'Regular Payments' ) + ->setType( 'REGULAR' ) + ->setFrequency( $inputs['payment_frequency'] ) + ->setFrequencyInterval( $inputs['payment_interval'] ) + ->setCycles( $inputs['payment_cycles'] )//cycle 0 + ->setAmount( new Currency( array( + 'value' => $inputs['price'], + 'currency' => $inputs['currency'] + ) ) ); + // Set merchant preferences + $merchantPreferences = new MerchantPreferences(); + $merchantPreferences->setReturnUrl( $inputs['success_url'] ) + ->setCancelUrl( $inputs['failed_url'] ) + ->setAutoBillAmount( 'yes' ) + ->setInitialFailAmountAction( 'CONTINUE' ) + ->setMaxFailAttempts( '0' ); +// ->setSetupFee(new Currency(array('value' => 1, 'currency' => 'USD'))); + $plan->setPaymentDefinitions( array( $paymentDefinition ) ); + $plan->setMerchantPreferences( $merchantPreferences ); + $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), env( 'PAYPAL_CLIENT_SECRET', '' ) ); + //create plan + try { + $createdPlan = $plan->create( $apiContext ); + try { + $patch = new Patch(); + $value = new PayPalModel( '{"state":"ACTIVE"}' ); + $patch->setOp( 'replace' ) + ->setPath( '/' ) + ->setValue( $value ); + $patchRequest = new PatchRequest(); + $patchRequest->addPatch( $patch ); + $createdPlan->update( $patchRequest, $apiContext ); + $plan = Plan::get( $createdPlan->getId(), $apiContext ); + // Create new agreement + $agreement = new Agreement(); + $agreement->setName( 'Base Agreement' ) + ->setDescription( 'Basic Agreement' ) +// ->setShippingAddress( $shippingAddress ) + ->setStartDate( date( "Y-m-d\TH:i:s\Z", strtotime( 'tomorrow' ) ) ); + $_plan = new Plan(); + $_plan->setId( $plan->getId() ); + $agreement->setPlan( $_plan ); + // Add payer type + $payer = new Payer(); + $payer->setPaymentMethod( 'paypal' ); + $agreement->setPayer( $payer ); +// Adding shipping details + // Create agreement + $agreement = $agreement->create( $apiContext ); + // Extract approval URL to redirect user + $approvalUrl = $agreement->getApprovalLink(); + $response['status'] = 'success'; + $response['data'] = $approvalUrl; + $response['messages'][] = 'Redirecting you to Paypal'; + + return $response; + // Output plan id +// echo $plan->getId(); + } catch ( PayPal\Exception\PayPalConnectionException $ex ) { + $response['status'] = 'failed'; + $response['errors'][] = $ex->getData(); + + return $response; +// die($ex); + } catch ( \Exception $ex ) { + $response['status'] = 'failed'; + $response['errors'][] = $ex; + + return $response; + } + } catch ( PayPal\Exception\PayPalConnectionException $ex ) { + $response['status'] = 'failed'; + $response['errors'][] = $ex->getData(); + + return $response; + } catch ( \Exception $ex ) { + $response['status'] = 'failed'; + $response['errors'][] = $ex; + + return $response; + } +// $payment_defination = + $response['status'] = 'success'; +// $response['data']['redirect_url'] = $payment->getApprovalLink(); + $response['messages'][] = 'Redirecting you to Paypal'; + + return $response; +} + + //---------------------------------------------------- + public function getApiContext( $clientId, $clientSecret ) { + // #### SDK configuration + // Register the sdk_config.ini file in current directory + // as the configuration source. + /* + if(!defined("PP_CONFIG_PATH")) { + define("PP_CONFIG_PATH", __DIR__); + } + */ + // ### Api context + // Use an ApiContext object to authenticate + // API calls. The clientId and clientSecret for the + // OAuthTokenCredential class can be retrieved from + // developer.paypal.com + $apiContext = new ApiContext( + new OAuthTokenCredential( + $clientId, + $clientSecret + ) + ); + // Comment this line out and uncomment the PP_CONFIG_PATH + // 'define' block if you want to use static file + // based configuration + $apiContext->setConfig( + array( + 'mode' => env( 'PAYPAL_MODE' ), + 'log.LogEnabled' => true, + 'log.FileName' => '../PayPal.log', + 'log.LogLevel' => 'DEBUG', + // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS + 'cache.enabled' => true, + //'cache.FileName' => '/PaypalCache' // for determining paypal cache directory + // 'http.CURLOPT_CONNECTTIMEOUT' => 30 + // 'http.headers.PayPal-Partner-Attribution-Id' => '123123123' + //'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory + ) + ); + // Partner Attribution Id + // Use this header if you are a PayPal partner. Specify a unique BN Code to receive revenue attribution. + // To learn more or to request a BN Code, contact your Partner Manager or visit the PayPal Partner Portal + // $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', '123123123'); + return $apiContext; + } + //---------------------------------------------------- + //----------------------------------------------------------------- + public function executePayment( Request $request ) { + $response = []; + if ( $request->has( 'paymentId' ) && $request->has( 'PayerID' ) ) { + + $paymentId = $request->paymentId; + $payerId = $request->PayerID; + $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), + env( 'PAYPAL_CLIENT_SECRET', '' ) ); + $payment = Payment::get( $paymentId, $apiContext ); + $execution = new PaymentExecution(); + $execution->setPayerId( $payerId ); + try { + $result = $payment->execute( $execution, $apiContext ); + $response['status'] = 'success'; + $response['data'] = $paymentId; + + return $response; + } catch ( \Exception $e ) { + + $response['status'] = 'failed'; + $response['errors'][] = $e->getMessage(); + + return $response; + } + } + + $response['status'] = 'failed'; + $response['errors'][] = 'Something went wrong. No Payment Id is received.'; + + return $response; + } + + //----------------------------------------------------------------- + public function executePlan( Request $request ) { + + if ( isset( $_GET['token'] ) ) { + $token = $request['token']; + $agreement = new \PayPal\Api\Agreement(); + try { + $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), + env( 'PAYPAL_CLIENT_SECRET', '' ) ); + // Execute agreement + $payment = $agreement->execute( $token, $apiContext ); + $response['status'] = 'success'; + $response['data'] = $agreement->getId(); + + return $response; + } catch ( PayPal\Exception\PayPalConnectionException $ex ) { + $response = []; + $response['status'] = 'failed'; + $response['errors'][] = $ex->getData(); + + return $response; +// die($ex); + } catch ( \Exception $ex ) { + $response = []; + $response['status'] = 'failed'; + $response['errors'][] = $ex->getData(); + + return $response; + } + } else { +// echo "user canceled agreement"; + $response = []; + $response['status'] = 'failed'; + $response['errors'][] = "User cancelled request"; + + return $response; + } + } + + //---------------------------------------------------- + public function setShippingAddress( $shippingAddress ) { + + $_shippingAddress = new ShippingAddress(); + if ( isset( $shippingAddress['line_one'] ) ) { + $_shippingAddress->setLine1( $shippingAddress['line_one'] ); + } else { + $response['status'] = 'failed'; + $response['errors'][] = 'Address Line 1 is required.'; + + return $response; + } + if ( isset( $shippingAddress['line_two'] ) ) { + $_shippingAddress->setLine2( $shippingAddress['line_two'] ); + } + if ( isset( $shippingAddress['city'] ) ) { + $_shippingAddress->setCity( $shippingAddress['city'] ); + } else { + $response['status'] = 'failed'; + $response['errors'][] = 'Address City is required.'; + + return $response; + } + if ( isset( $shippingAddress['zip'] ) ) { + $_shippingAddress->setPostalCode( $shippingAddress['zip'] ); + } else { + $response['status'] = 'failed'; + $response['errors'][] = 'Address Zip is required.'; + + return $response; + } + if ( isset( $shippingAddress['country'] ) ) { + $_shippingAddress->setCountryCode( $shippingAddress['country'] ); + } else { + $response['status'] = 'failed'; + $response['errors'][] = 'Address Country is required.'; + + return $response; + } + if ( isset( $shippingAddress['state'] ) ) { + $_shippingAddress->setCountryCode( $shippingAddress['state'] ); + } else { + $response['status'] = 'failed'; + $response['errors'][] = 'Address state is required.'; + + return $response; + } + if ( isset( $shippingAddress['mobile'] ) ) { + $_shippingAddress->setPhone( $shippingAddress['mobile'] ); + } + if ( isset( $shippingAddress['name'] ) ) { + $_shippingAddress->setRecipientName( $shippingAddress['name'] ); + } + $response['status'] = 'success'; + $response['data'] = $_shippingAddress; + + return $response; +// return $_shippingAddress; + } + //---------------------------------------------------------- + + public function subscription($customer, + $card, + $address, + $price_id, + $return_url) + { + + $validate = self::validation($customer, + $card, $address, $price_id, $return_url, null,true); + + if(isset($validate['status']) && $validate['status'] == 'failed') + { + return $validate; + } + + try{ + + $customer_inputs = [ + 'email' => $customer['email'], + 'name' => $customer['name'], + 'address' => $address + ]; + + $card['number'] = str_replace( + '-', '', $card['number'] + ); + + $token = Stripe::tokens()->create([ + 'card' => $card, + ]); + + $customer_inputs['source'] = $token['id']; + + $customer = Stripe::customers()->create($customer_inputs); + + $method_inputs = [ + "type" => 'card', + "card" => $card + ]; + + $payment_method = Stripe::paymentMethods()->create($method_inputs); + + $customer_iD = $customer['id']; + $payment_method_iD = $payment_method['id']; + + Stripe::paymentMethods()->attach($payment_method_iD, $customer_iD); + + $subscription = Stripe::subscriptions()->create( + $customer_iD, + [ + 'plan' => $price_id, + 'payment_behavior' => 'default_incomplete', + 'expand' => ['latest_invoice.payment_intent'], + ] + ); + + $invoice = Stripe::invoices()->find($subscription['latest_invoice']['id']); + + + $pa_intent = Stripe::paymentIntents()->confirm( + $invoice['payment_intent'], + [ + "return_url" => $return_url + ] + ); + + $response['status'] = 'success'; + $response['data'] = $pa_intent; + + + }catch(\Exception $e) + { + $response['status'] = 'failed'; + $response['errors'][] = $e->getMessage(); + } + + return $response; + + } + //---------------------------------------------------------- + + public function createProduct(Request $request) + { + $inputs = $request->all(); + + $rules = array( + 'name' => 'required', + 'description' => 'required' + ); + + $validator = \Validator::make( $inputs, $rules); + if ( $validator->fails() ) { + + $errors = errorsToArray($validator->errors()); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } + + try{ + + $product = Stripe::products()->create([ + 'name' => $inputs['name'], + 'description' => $inputs['description'], + 'type' => 'service' + ]); + + $response['status'] = 'success'; + $response['data'] = $product; + + }catch(\Exception $e) + { + $response['status'] = 'failed'; + $response['errors'][] = $e->getMessage(); + } + + return $response; + + } + //---------------------------------------------------------- + + public function createPrice(Request $request) + { + $inputs = $request->all(); + + $rules = array( + 'product_id' => 'required', + 'amount' => 'required', + 'currency' => 'required', + 'interval' => 'required' + ); + + $validator = \Validator::make( $inputs, $rules); + if ( $validator->fails() ) { + + $errors = errorsToArray($validator->errors()); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } + + try{ + + $product = Stripe::prices()->create([ + 'unit_amount' => $inputs['amount'], + 'currency' => $inputs['currency'], + 'product' => $inputs['product_id'], + 'recurring' => [ + 'interval' => $inputs['interval'] + ] + ]); + + $response['status'] = 'success'; + $response['data'] = $product; + + }catch(\Exception $e) + { + $response['status'] = 'failed'; + $response['errors'][] = $e->getMessage(); + } + + return $response; + + } + //---------------------------------------------------------- + + public function findProductByName($name) + { + + if(!$name){ + $response['status'] = 'failed'; + $response['errors'] = 'The name field is required.'; + return $response; + } + + try{ + + $product_val = null; + + $data = [ + 'active' => true + ]; + + $products = Stripe::products()->all($data); + + foreach ($products['data'] as $product){ + + if($product['name'] == $name){ + $product_val = $product; + } + + } + + if(!$product_val){ + $response['status'] = 'failed'; + $response['errors'][] = 'No Product Found'; + return $response; + } + + $response['status'] = 'success'; + $response['data'] = $product_val; + + + }catch(\Exception $e) + { + $response['status'] = 'failed'; + $response['errors'][] = $e->getMessage(); + } + + return $response; + + } + //---------------------------------------------------------- + + public function getProductPrice($product_id, $value = null, $by = 'amount') + { + + if(!$product_id){ + $response['status'] = 'failed'; + $response['errors'] = 'The product id field is required.'; + return $response; + } + + try{ + + $price_val = null; + + $data = [ + 'active' => true + ]; + + $prices = Stripe::prices()->all($data); + + foreach ($prices['data'] as $price){ + + if($price['product'] == $product_id){ + if($value && $by){ + + switch ($by) + { + //------------------------------------ + case 'amount': + + if($price['unit_amount'] == $value){ + $price_val = $price; + } + + break; + + //------------------------------------ + case 'currency': + + if($price[$by] == $value){ + $price_val = $price; + } + + break; + + //------------------------------------ + case 'interval': + + if($price['recurring'][$by] == $value){ + $price_val = $price; + } + + break; + //------------------------------------ + + } + + }else{ + $price_val = $price; + } + } + + } + + if(!$price_val){ + $response['status'] = 'failed'; + $response['errors'][] = 'No Price Found'; + return $response; + } + + $response['status'] = 'success'; + $response['data'] = $price_val; + + + }catch(\Exception $e) + { + $response['status'] = 'failed'; + $response['errors'][] = $e->getMessage(); + } + + return $response; + + } + //---------------------------------------------------------- + + //---------------------------------------------------------- + public static function validation($customer, + $card, + $address, + $price_id, + $return_url, + $package, + $is_subscription = false){ + + $rules = array( + 'name' => 'required', + 'email' => 'required|email:rfc,dns' + ); + + $validator = \Validator::make( $customer, $rules); + if ( $validator->fails() ) { + + $errors = errorsToArray($validator->errors()); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } + + $rules = array( + 'number' => 'required', + 'exp_month' => 'required', + 'exp_year' => 'required', + 'cvc' => 'required' + ); + + $validator = \Validator::make( $card, $rules); + if ( $validator->fails() ) { + + $errors = errorsToArray($validator->errors()); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } + + if(!$is_subscription && $package){ + $rules = array( + 'currency' => 'required', + 'amount' => 'required', + 'description' => 'required' + ); + + $validator = \Validator::make( $package, $rules); + if ( $validator->fails() ) { + + $errors = errorsToArray($validator->errors()); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } + } + + $rules = array( + 'line1' => 'required', + 'country' => 'required', + ); + + $validator = \Validator::make( $address, $rules); + if ( $validator->fails() ) { + + $errors = errorsToArray($validator->errors()); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } + + if($is_subscription && !$price_id){ + $response['status'] = 'failed'; + $response['errors'] = 'The price id field is required.'; + return $response; + } + + if(!$return_url){ + $response['status'] = 'failed'; + $response['errors'] = 'The return url field is required.'; + return $response; + } + + } + //---------------------------------------------------------- + + +} From c5b23e7257f20d7cc3fbfdfb6d56620749efff5e Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Fri, 2 Dec 2022 12:15:47 +0530 Subject: [PATCH 05/26] Updated: Paypal methods --- Libraries/VaahPayPal.php | 237 +++++++++++++++++++++++++++++++++------ 1 file changed, 202 insertions(+), 35 deletions(-) diff --git a/Libraries/VaahPayPal.php b/Libraries/VaahPayPal.php index 90d7c98..3db4fba 100644 --- a/Libraries/VaahPayPal.php +++ b/Libraries/VaahPayPal.php @@ -2,6 +2,9 @@ namespace WebReinvent\VaahExtend\Libraries; use Cartalyst\Stripe\Laravel\Facades\Stripe; +use Illuminate\Support\Facades\Log; +use PayPal\Api\OpenIdTokeninfo; +use PayPal\Api\OpenIdUserinfo; use Srmklive\PayPal\Services\ExpressCheckout; @@ -25,11 +28,173 @@ use PayPal\Common\PayPalModel; use PayPal\Rest\ApiContext; +use Srmklive\PayPal\Services\PayPal as PayPalClient; + class VaahPayPal{ //---------------------------------------------------------- + public function pay($inputs){ +// $user['email'] = $inputs['stripe']['email']; + $user['username'] = $inputs['user']['username']; +// $user['address'] = $inputs['stripe']['address']; + + + $payment = $inputs['stripe']['payment']; + //set user data +// $payerInfo = new \PayPal\Api\PayerInfo(); +// $address = new \PayPal\Api\Address(); +// $address->setLine1($user['address']['line1']) +// ->setCity($user['address']['city']) +// ->setState($user['address']['state']) +// ->setPostalCode($user['address']['postal_code']) +// ->setCountryCode($user['address']['country']); + +// $payerInfo->setEmail($user['email']) +// ->setFirstName($user['name']) +// ->setBillingAddress($address); + + $payer = new \PayPal\Api\Payer(); + $payer->setPaymentMethod("paypal"); +// ->setPayerInfo($payerInfo); + + $item = new \PayPal\Api\Item(); + $item->setName($payment['description']) + ->setCurrency($payment['currency']) + ->setPrice($payment['amount']) + ->setQuantity(1); + + $itemList = new \PayPal\Api\ItemList(); + $itemList->setItems(array($item)); + +// $details = new \PayPal\Api\Details(); +// $details->setTax(0)->setSubtotal($payment['amount']); + + $amount = new \PayPal\Api\Amount(); + $total = $payment['amount'] * $item->getQuantity(); + $amount->setCurrency($payment['currency']) + ->setTotal($total); + + + $transaction = new \PayPal\Api\Transaction(); + $transaction->setAmount($amount)->setItemList($itemList) + ->setDescription($payment['description']) + ->setInvoiceNumber(uniqid()); + + $returnUrl = url('/').'#/paypal/complete'; + $cancelUrl = url('/').'#/paypal/cancel'; + $redirectUrls = new \PayPal\Api\RedirectUrls(); + $redirectUrls->setReturnUrl($returnUrl) + ->setCancelUrl($cancelUrl); + + $payment = new \PayPal\Api\Payment(); + $payment->setIntent("sale") + ->setPayer($payer) + ->setRedirectUrls($redirectUrls) + ->setTransactions(array($transaction)); + + + $apiContext = $this->getApiContext( + env('PAYPAL_SANDBOX_CLIENT_ID'), + env('PAYPAL_SANDBOX_CLIENT_SECRET') + ); + try { + $resp = $payment->create($apiContext); + $approvalUrl = $resp->getApprovalLink(); + $response = []; + $response['status'] = 'success'; + $response['data']['approval_url'] = $approvalUrl; + $response['data']['payment_id'] = $resp->getId(); + $response['data']['token'] = $resp->getToken(); + return $response; + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = $ex->getData(); + return $response; + } catch (\Exception $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = $ex->getMessage(); + return $response; + } + } + public function getUserInfo(){ + $apiContext = $this->getApiContext( + env('PAYPAL_SANDBOX_CLIENT_ID'), + env('PAYPAL_SANDBOX_CLIENT_SECRET') + ); + try { + $token = $apiContext->getCredential()->getAccessToken($apiContext); + $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $apiContext); + $response = []; + $response['status'] = 'success'; + $response['data'] = $user->toArray(); + return $response; + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = json_decode($ex->getData())->message; + return $response; + } catch (\Exception $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = $ex->getMessage(); + return $response; + } + } //---------------------------------------------------------- - + public function executePayment($paymentId, $payerId) + { + $apiContext = $this->getApiContext( + env('PAYPAL_SANDBOX_CLIENT_ID'), + env('PAYPAL_SANDBOX_CLIENT_SECRET') + ); + try { + $payment = \PayPal\Api\Payment::get($paymentId, $apiContext); + $execution = new \PayPal\Api\PaymentExecution(); + $execution->setPayerId($payerId); + $result = $payment->execute($execution, $apiContext); + $response = []; + $response['status'] = 'success'; + $response['data'] = $result->toArray(); + return $response; + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = json_decode($ex->getData())->message; + return $response; + } catch (\Exception $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = $ex->getMessage(); + return $response; + } + } + //---------------------------------------------------------- + public function getPaymentDetailByPaymentID($paymentId) + { + $apiContext = $this->getApiContext( + env('PAYPAL_SANDBOX_CLIENT_ID'), + env('PAYPAL_SANDBOX_CLIENT_SECRET') + ); + try { + $payment = \PayPal\Api\Payment::get($paymentId, $apiContext); + $response = []; + $response['status'] = 'success'; + $response['data'] = $payment->toArray(); + return $response; + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = json_decode($ex->getData())->message; + return $response; + } catch (\Exception $ex) { + $response = []; + $response['status'] = 'failed'; + $response['error'] = $ex->getMessage(); + return $response; + } + } //---------------------------------------------------- public function payPalOnetime( $inputs, $shippingAddress = null ) { @@ -129,7 +294,7 @@ public function payPalOnetime( $inputs, $shippingAddress = null ) { if ( $address ) { $itemList->setShippingAddress( $address ); } - $_amount = $inputs['price'] + $tax; + $_amount = ($inputs['price'] * $inputs['item_quantity']) + $tax; //Payment Amount $amount = new Amount(); $amount->setCurrency( $inputs['currency'] ) @@ -150,6 +315,7 @@ public function payPalOnetime( $inputs, $shippingAddress = null ) { // A Payment Resource; create one using // the above types and intent as 'sale' //die; +// return $transaction; $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl( $inputs['success_url'] ) ->setCancelUrl( $inputs['failed_url'] ); @@ -163,7 +329,7 @@ public function payPalOnetime( $inputs, $shippingAddress = null ) { // Create a payment by posting to the APIService // using a valid ApiContext // The return object contains the status; - $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), env( 'PAYPAL_CLIENT_SECRET', '' ) ); + $apiContext = $this->getApiContext( env( 'PAYPAL_SANDBOX_CLIENT_ID', '' ), env( 'PAYPAL_SANDBOX_CLIENT_SECRET', '' ) ); $payment->create( $apiContext ); $approved_url = $payment->getApprovalLink(); $approved_url = parse_url( $approved_url ); @@ -342,7 +508,8 @@ public function getApiContext( $clientId, $clientSecret ) { new OAuthTokenCredential( $clientId, $clientSecret - ) + ), + ); // Comment this line out and uncomment the PP_CONFIG_PATH // 'define' block if you want to use static file @@ -369,37 +536,37 @@ public function getApiContext( $clientId, $clientSecret ) { } //---------------------------------------------------- //----------------------------------------------------------------- - public function executePayment( Request $request ) { - $response = []; - if ( $request->has( 'paymentId' ) && $request->has( 'PayerID' ) ) { - - $paymentId = $request->paymentId; - $payerId = $request->PayerID; - $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), - env( 'PAYPAL_CLIENT_SECRET', '' ) ); - $payment = Payment::get( $paymentId, $apiContext ); - $execution = new PaymentExecution(); - $execution->setPayerId( $payerId ); - try { - $result = $payment->execute( $execution, $apiContext ); - $response['status'] = 'success'; - $response['data'] = $paymentId; - - return $response; - } catch ( \Exception $e ) { - - $response['status'] = 'failed'; - $response['errors'][] = $e->getMessage(); - - return $response; - } - } - - $response['status'] = 'failed'; - $response['errors'][] = 'Something went wrong. No Payment Id is received.'; - - return $response; - } +// public function executePayment( Request $request ) { +// $response = []; +// if ( $request->has( 'paymentId' ) && $request->has( 'PayerID' ) ) { +// +// $paymentId = $request->paymentId; +// $payerId = $request->PayerID; +// $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), +// env( 'PAYPAL_CLIENT_SECRET', '' ) ); +// $payment = Payment::get( $paymentId, $apiContext ); +// $execution = new PaymentExecution(); +// $execution->setPayerId( $payerId ); +// try { +// $result = $payment->execute( $execution, $apiContext ); +// $response['status'] = 'success'; +// $response['data'] = $paymentId; +// +// return $response; +// } catch ( \Exception $e ) { +// +// $response['status'] = 'failed'; +// $response['errors'][] = $e->getMessage(); +// +// return $response; +// } +// } +// +// $response['status'] = 'failed'; +// $response['errors'][] = 'Something went wrong. No Payment Id is received.'; +// +// return $response; +// } //----------------------------------------------------------------- public function executePlan( Request $request ) { From 51e6a7c2d382b8f0b58ae677bc0a9b2a724e46dc Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Fri, 2 Dec 2022 14:04:30 +0530 Subject: [PATCH 06/26] Fixed : Wrong vars --- Libraries/VaahPayPal.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Libraries/VaahPayPal.php b/Libraries/VaahPayPal.php index 3db4fba..435ccd2 100644 --- a/Libraries/VaahPayPal.php +++ b/Libraries/VaahPayPal.php @@ -32,6 +32,23 @@ class VaahPayPal{ + private $apiContext; + private $mode; + private $client_id; + private $client_secret; + private $return_url; + private $cancel_url; + + public function __construct() + { + $this->mode = env('PAYPAL_MODE'); + $this->client_id = $this->mode == 'sandbox' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_LIVE_CLIENT_ID'); + $this->client_secret = $this->mode == 'sandbox' ? env('PAYPAL_SANDBOX_CLIENT_SECRET') : env('PAYPAL_LIVE_CLIENT_SECRET'); + $this->return_url = url('/').'#/paypal/complete'; + $this->cancel_url = url('/').'#/paypal/cancel'; + $this->apiContext = $this->getApiContext($this->client_id, $this->client_secret); + } + //---------------------------------------------------------- public function pay($inputs){ // $user['email'] = $inputs['stripe']['email']; From 818fe288587b6992caf3e3c1c98c84633950bfe2 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Fri, 2 Dec 2022 14:05:33 +0530 Subject: [PATCH 07/26] Updated: Code refactor --- Libraries/VaahPayPal.php | 92 ++++++++-------------------------------- 1 file changed, 17 insertions(+), 75 deletions(-) diff --git a/Libraries/VaahPayPal.php b/Libraries/VaahPayPal.php index 435ccd2..9339293 100644 --- a/Libraries/VaahPayPal.php +++ b/Libraries/VaahPayPal.php @@ -2,10 +2,7 @@ namespace WebReinvent\VaahExtend\Libraries; use Cartalyst\Stripe\Laravel\Facades\Stripe; -use Illuminate\Support\Facades\Log; -use PayPal\Api\OpenIdTokeninfo; use PayPal\Api\OpenIdUserinfo; -use Srmklive\PayPal\Services\ExpressCheckout; use Illuminate\Http\Request; @@ -28,8 +25,6 @@ use PayPal\Common\PayPalModel; use PayPal\Rest\ApiContext; -use Srmklive\PayPal\Services\PayPal as PayPalClient; - class VaahPayPal{ private $apiContext; @@ -55,68 +50,46 @@ public function pay($inputs){ $user['username'] = $inputs['user']['username']; // $user['address'] = $inputs['stripe']['address']; - $payment = $inputs['stripe']['payment']; - //set user data -// $payerInfo = new \PayPal\Api\PayerInfo(); -// $address = new \PayPal\Api\Address(); -// $address->setLine1($user['address']['line1']) -// ->setCity($user['address']['city']) -// ->setState($user['address']['state']) -// ->setPostalCode($user['address']['postal_code']) -// ->setCountryCode($user['address']['country']); - -// $payerInfo->setEmail($user['email']) -// ->setFirstName($user['name']) -// ->setBillingAddress($address); $payer = new \PayPal\Api\Payer(); $payer->setPaymentMethod("paypal"); -// ->setPayerInfo($payerInfo); - + //set item info $item = new \PayPal\Api\Item(); $item->setName($payment['description']) ->setCurrency($payment['currency']) ->setPrice($payment['amount']) ->setQuantity(1); - + //set item list $itemList = new \PayPal\Api\ItemList(); $itemList->setItems(array($item)); -// $details = new \PayPal\Api\Details(); -// $details->setTax(0)->setSubtotal($payment['amount']); - + //set amount $amount = new \PayPal\Api\Amount(); $total = $payment['amount'] * $item->getQuantity(); $amount->setCurrency($payment['currency']) ->setTotal($total); - + //set transaction $transaction = new \PayPal\Api\Transaction(); $transaction->setAmount($amount)->setItemList($itemList) ->setDescription($payment['description']) ->setInvoiceNumber(uniqid()); - - $returnUrl = url('/').'#/paypal/complete'; - $cancelUrl = url('/').'#/paypal/cancel'; + //set redirect urls $redirectUrls = new \PayPal\Api\RedirectUrls(); - $redirectUrls->setReturnUrl($returnUrl) - ->setCancelUrl($cancelUrl); - + $redirectUrls->setReturnUrl($this->return_url) + ->setCancelUrl($this->cancel_url); + //set payment $payment = new \PayPal\Api\Payment(); $payment->setIntent("sale") ->setPayer($payer) ->setRedirectUrls($redirectUrls) ->setTransactions(array($transaction)); - - $apiContext = $this->getApiContext( - env('PAYPAL_SANDBOX_CLIENT_ID'), - env('PAYPAL_SANDBOX_CLIENT_SECRET') - ); + //create payment with valid api context try { - $resp = $payment->create($apiContext); - $approvalUrl = $resp->getApprovalLink(); + $resp = $payment->create($this->apiContext); + $approvalUrl = $resp->getApprovalLink(); //approval url $response = []; $response['status'] = 'success'; $response['data']['approval_url'] = $approvalUrl; @@ -135,14 +108,12 @@ public function pay($inputs){ return $response; } } + //---------------------------------------------------------- public function getUserInfo(){ - $apiContext = $this->getApiContext( - env('PAYPAL_SANDBOX_CLIENT_ID'), - env('PAYPAL_SANDBOX_CLIENT_SECRET') - ); + //getting user details try { - $token = $apiContext->getCredential()->getAccessToken($apiContext); - $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $apiContext); + $token = $this->apiContext->getCredential()->getAccessToken($this->apiContext); //get access token + $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $this->apiContext); $response = []; $response['status'] = 'success'; $response['data'] = $user->toArray(); @@ -162,15 +133,11 @@ public function getUserInfo(){ //---------------------------------------------------------- public function executePayment($paymentId, $payerId) { - $apiContext = $this->getApiContext( - env('PAYPAL_SANDBOX_CLIENT_ID'), - env('PAYPAL_SANDBOX_CLIENT_SECRET') - ); try { - $payment = \PayPal\Api\Payment::get($paymentId, $apiContext); + $payment = \PayPal\Api\Payment::get($paymentId, $this->apiContext); $execution = new \PayPal\Api\PaymentExecution(); $execution->setPayerId($payerId); - $result = $payment->execute($execution, $apiContext); + $result = $payment->execute($execution, $this->apiContext); $response = []; $response['status'] = 'success'; $response['data'] = $result->toArray(); @@ -188,31 +155,6 @@ public function executePayment($paymentId, $payerId) } } //---------------------------------------------------------- - public function getPaymentDetailByPaymentID($paymentId) - { - $apiContext = $this->getApiContext( - env('PAYPAL_SANDBOX_CLIENT_ID'), - env('PAYPAL_SANDBOX_CLIENT_SECRET') - ); - try { - $payment = \PayPal\Api\Payment::get($paymentId, $apiContext); - $response = []; - $response['status'] = 'success'; - $response['data'] = $payment->toArray(); - return $response; - } catch (\PayPal\Exception\PayPalConnectionException $ex) { - $response = []; - $response['status'] = 'failed'; - $response['error'] = json_decode($ex->getData())->message; - return $response; - } catch (\Exception $ex) { - $response = []; - $response['status'] = 'failed'; - $response['error'] = $ex->getMessage(); - return $response; - } - } - //---------------------------------------------------- public function payPalOnetime( $inputs, $shippingAddress = null ) { $inputs = [ From 435246dc38610c6eae126af87b7daeb4c2bf9537 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Fri, 2 Dec 2022 18:31:16 +0530 Subject: [PATCH 08/26] Updated: VaahPaypal generic --- Libraries/VaahPayPal.php | 953 ++++----------------------------------- 1 file changed, 83 insertions(+), 870 deletions(-) diff --git a/Libraries/VaahPayPal.php b/Libraries/VaahPayPal.php index 9339293..d4225a8 100644 --- a/Libraries/VaahPayPal.php +++ b/Libraries/VaahPayPal.php @@ -1,7 +1,6 @@ mode = env('PAYPAL_MODE'); - $this->client_id = $this->mode == 'sandbox' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_LIVE_CLIENT_ID'); - $this->client_secret = $this->mode == 'sandbox' ? env('PAYPAL_SANDBOX_CLIENT_SECRET') : env('PAYPAL_LIVE_CLIENT_SECRET'); - $this->return_url = url('/').'#/paypal/complete'; - $this->cancel_url = url('/').'#/paypal/cancel'; + $this->mode = $mode; + $this->client_id = $client_id; + $this->client_secret = $client_secret; + $this->return_url = $return_url; + $this->cancel_url = $cancel_url; $this->apiContext = $this->getApiContext($this->client_id, $this->client_secret); } //---------------------------------------------------------- public function pay($inputs){ -// $user['email'] = $inputs['stripe']['email']; - $user['username'] = $inputs['user']['username']; -// $user['address'] = $inputs['stripe']['address']; - - $payment = $inputs['stripe']['payment']; - + $rules = [ + 'name' => 'required', + 'amount' => 'required', + 'currency' => 'required', + 'description' => 'required', + 'quantity' => 'required', + ]; + $validator = \Validator::make($inputs, $rules); + if ($validator->fails()) { + $errors = $validator->errors(); + $response['status'] = 'failed'; + $response['errors'] = $errors; + return $response; + } $payer = new \PayPal\Api\Payer(); $payer->setPaymentMethod("paypal"); //set item info $item = new \PayPal\Api\Item(); - $item->setName($payment['description']) - ->setCurrency($payment['currency']) - ->setPrice($payment['amount']) - ->setQuantity(1); + $item->setName($inputs['name']) + ->setDescription($inputs['description']) + ->setCurrency($inputs['currency']) + ->setPrice($inputs['amount']) + ->setQuantity($inputs['quantity']); //set item list $itemList = new \PayPal\Api\ItemList(); $itemList->setItems(array($item)); + //details + $details = new \PayPal\Api\Details(); + $shipping = $inputs['shipping'] ?? 0; + $tax = $inputs['tax'] ?? 0; + + $subtotal = ($inputs['amount'] * $inputs['quantity']) + $shipping + $tax; + $details->setShipping($shipping) + ->setTax($tax) + ->setSubtotal($subtotal); //set amount $amount = new \PayPal\Api\Amount(); - $total = $payment['amount'] * $item->getQuantity(); - $amount->setCurrency($payment['currency']) - ->setTotal($total); + $total = $inputs['amount'] * $item->getQuantity(); + $amount->setCurrency($inputs['currency']) + ->setTotal($total) + ->setDetails($details); //set transaction $transaction = new \PayPal\Api\Transaction(); $transaction->setAmount($amount)->setItemList($itemList) - ->setDescription($payment['description']) + ->setDescription($inputs['description']) ->setInvoiceNumber(uniqid()); //set redirect urls $redirectUrls = new \PayPal\Api\RedirectUrls(); @@ -86,7 +110,7 @@ public function pay($inputs){ ->setRedirectUrls($redirectUrls) ->setTransactions(array($transaction)); - //create payment with valid api context + //create payment with valid api context try { $resp = $payment->create($this->apiContext); $approvalUrl = $resp->getApprovalLink(); //approval url @@ -99,356 +123,62 @@ public function pay($inputs){ } catch (\PayPal\Exception\PayPalConnectionException $ex) { $response = []; $response['status'] = 'failed'; - $response['error'] = $ex->getData(); + $response['errors'] = $ex->getData(); return $response; } catch (\Exception $ex) { $response = []; $response['status'] = 'failed'; - $response['error'] = $ex->getMessage(); + $response['errors'] = $ex->getMessage(); return $response; } } //---------------------------------------------------------- - public function getUserInfo(){ + public function getUserInfo(){ //getting user details - try { - $token = $this->apiContext->getCredential()->getAccessToken($this->apiContext); //get access token - $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $this->apiContext); - $response = []; - $response['status'] = 'success'; - $response['data'] = $user->toArray(); - return $response; - } catch (\PayPal\Exception\PayPalConnectionException $ex) { - $response = []; - $response['status'] = 'failed'; - $response['error'] = json_decode($ex->getData())->message; - return $response; - } catch (\Exception $ex) { - $response = []; - $response['status'] = 'failed'; - $response['error'] = $ex->getMessage(); - return $response; - } - } - //---------------------------------------------------------- - public function executePayment($paymentId, $payerId) - { - try { - $payment = \PayPal\Api\Payment::get($paymentId, $this->apiContext); - $execution = new \PayPal\Api\PaymentExecution(); - $execution->setPayerId($payerId); - $result = $payment->execute($execution, $this->apiContext); - $response = []; - $response['status'] = 'success'; - $response['data'] = $result->toArray(); - return $response; - } catch (\PayPal\Exception\PayPalConnectionException $ex) { - $response = []; - $response['status'] = 'failed'; - $response['error'] = json_decode($ex->getData())->message; - return $response; - } catch (\Exception $ex) { - $response = []; - $response['status'] = 'failed'; - $response['error'] = $ex->getMessage(); - return $response; - } - } - //---------------------------------------------------------- - public function payPalOnetime( $inputs, $shippingAddress = null ) { - - $inputs = [ - 'price' => 20.00, - 'tax' => 10.00, - 'success_url' => 'http://localhost/vikram/morapp/public', - //route for redirection after payment success. - 'failed_url' => 'http://localhost/vikram/morapp/public', - //route for redirection after payment failure. - 'item_name' => "Item one", - 'item_sku' => "item-one", - 'item_desc' => "This is the product", - 'currency' => "USD", - 'item_quantity' => 5, - 'invoice_number' => uniqid(), - 'payment_frequency' => 'Month', - // can be `WEEK`, `DAY`, `YEAR`, `MONTH`. - 'payment_interval' => 1, - // in how many months, days, or week you to execute the same payment. - 'cycles' => 12, - // in how many months, days, or week you to execute the same payment. 0 if plan type is infinite - 'plan_type' => 12, - // Allowed values: `FIXED`, `INFINITE` infinite is for subscription or fixed for EMIs. - ]; - - $rules = array( - 'price' => 'required|numeric', -// 'tax' => 'required|numeric', - 'success_url' => 'required', - 'failed_url' => 'required', - 'item_name' => 'required', - 'item_sku' => 'required', - 'currency' => 'required', - 'item_quantity' => 'required|integer', - 'invoice_number' => 'required', - ); - $messages = [ - 'price.required' => 'Price is required.', - 'item_quantity.required' => 'Item quantity is required.', - 'tax.required' => 'Tax is required.', - 'price.numeric' => 'Price should be in Numbers.', - 'item_quantity.numeric' => 'Item Quantity should be in Numbers.', - 'tax.numeric' => 'Tax should be in Numbers.', - 'success_url.required' => 'Success url is required.', - 'failed_url.required' => 'Failure url is required.', - 'item_name.required' => 'Item name is required.', - 'item_sku.required' => 'Item sku is required.', - 'currency.required' => 'Currency is required.', - 'invoice_number.required' => 'Invoice number is required.', - ]; - $validator = \Validator::make( $inputs, $rules, $messages ); - if ( $validator->fails() ) { - - $errors = $validator->errors(); + try { + $token = $this->apiContext->getCredential()->getAccessToken($this->apiContext); //get access token + $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $this->apiContext); + $response = []; + $response['status'] = 'success'; + $response['data'] = $user->toArray(); + return $response; + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + $response = []; $response['status'] = 'failed'; - $response['errors'] = $errors; - + $response['errors'] = $ex->getData(); return $response; - } - $response = []; - $address = null; - if ( $shippingAddress && is_array( $shippingAddress ) ) { - $res = $this->setShippingAddress( $shippingAddress ); - if ( $res['status'] === 'failed' ) { - return $res; - } - if ( $res['status'] === 'success' ) { - $address = $res['data']; - } - } - - $tax = 0; - - if (isset($inputs['tax']) && $inputs['tax']>0){ - if (!is_numeric($inputs['tax'])){ - $response['status'] = 'failed'; - $response['errors'][] = 'Tax should be in numbers'; - - return $response; - } - $tax = $inputs['tax']; - } - - $payer = new Payer(); - $payer->setPaymentMethod( "paypal" ); - $item = new Item(); - $item->setName( $inputs['item_name'] ) - ->setCurrency( $inputs['currency'] ) - ->setSku( $inputs['item_sku'] ) - ->setQuantity( $inputs['item_quantity'] ) - ->setPrice( $inputs['price'] ); - $details = new \PayPal\Api\Details(); - $details->setTax( $tax )->setSubtotal( $inputs['price'] ); - $itemList = new ItemList(); - $itemList->setItems( [ $item ] ); - if ( $address ) { - $itemList->setShippingAddress( $address ); - } - $_amount = ($inputs['price'] * $inputs['item_quantity']) + $tax; - //Payment Amount - $amount = new Amount(); - $amount->setCurrency( $inputs['currency'] ) - // the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping). - ->setTotal( ( $_amount ) )->setDetails( $details ); - // ### Transaction - // A transaction defines the contract of a - // payment - what is the payment for and who - // is fulfilling it. Transaction is created with - // a `Payee` and `Amount` types - //die; - $transaction = new Transaction(); - $transaction->setAmount( $amount ) - ->setItemList( $itemList ) -// ->setDescription("Assignable.io Cart ID: ".$cart->uid) - ->setInvoiceNumber( $inputs['invoice_number'] ); - // ### Payment - // A Payment Resource; create one using - // the above types and intent as 'sale' - //die; -// return $transaction; - $redirectUrls = new RedirectUrls(); - $redirectUrls->setReturnUrl( $inputs['success_url'] ) - ->setCancelUrl( $inputs['failed_url'] ); - $payment = new Payment(); - $payment->setIntent( "sale" ) - ->setPayer( $payer ) - ->setRedirectUrls( $redirectUrls ) - ->setTransactions( [ $transaction ] ); - try { - // ### Create Payment - // Create a payment by posting to the APIService - // using a valid ApiContext - // The return object contains the status; - $apiContext = $this->getApiContext( env( 'PAYPAL_SANDBOX_CLIENT_ID', '' ), env( 'PAYPAL_SANDBOX_CLIENT_SECRET', '' ) ); - $payment->create( $apiContext ); - $approved_url = $payment->getApprovalLink(); - $approved_url = parse_url( $approved_url ); - parse_str( $approved_url['query'], $approved_query_params ); - } catch ( \Exception $ex ) { - - $response['status'] = 'failed'; - $response['errors'][] = $ex->getMessage(); - + } catch (\Exception $ex) { + $response = []; + $response['status'] = 'failed'; + $response['errors'] = $ex->getMessage(); return $response; } - $response['status'] = 'success'; - $response['data']['redirect_url'] = $payment->getApprovalLink(); - $response['messages'][] = 'Redirecting you to PayPal'; - - return $response; - } public function payPalSubscription( $inputs ) { - - $rules = array( - 'price' => 'required|numeric', -// 'tax' => 'required|numeric', - 'success_url' => 'required', - 'plan_type' => 'required', - 'failed_url' => 'required', - 'item_name' => 'required', - 'item_sku' => 'required', - 'item_desc' => 'required', - 'currency' => 'required', - 'item_quantity' => 'required|integer', - 'invoice_number' => 'required', - 'payment_frequency' => 'required', - 'payment_interval' => 'required|integer', - 'payment_cycles' => 'required|integer', - ); - $messages = [ - 'price.required' => 'Price is required.', - 'item_quantity.required' => 'Item quantity is required.', - 'tax.required' => 'Tax is required.', - 'price.numeric' => 'Price should be in Numbers.', - 'item_quantity.numeric' => 'Item Quantity should be in Numbers.', - 'tax.numeric' => 'Tax should be in Numbers.', - 'success_url.required' => 'Success url is required.', - 'failed_url.required' => 'Failure url is required.', - 'item_name.required' => 'Item name is required.', - 'item_desc.required' => 'Item description is required.', - 'item_sku.required' => 'Item sku is required.', - 'currency.required' => 'Currency is required.', - 'invoice_number.required' => 'Invoice number is required.', - 'plan_type.required' => 'Plan Type is required this should be infinite or fixed.', - 'payment_interval.required' => 'Payment interval is required.', - 'payment_frequency.required' => 'Payment frequency is required.', - 'payment_cycles.integer' => 'Payment cycles should be in integer.', - 'payment_interval.integer' => 'Payment interval should be in integer.', - 'payment_cycles.required' => 'Payment Cycle is required.', - ]; - $validator = \Validator::make( $inputs, $rules, $messages ); - if ( $validator->fails() ) { - - $errors = $validator->errors(); - $response['status'] = 'failed'; - $response['errors'] = $errors; - - return $response; } - $plan = new Plan(); - $plan->setName( $inputs['item_name'] ) - ->setDescription( $inputs['item_desc'] ) - ->setType( $inputs['plan_type'] ); //infinite or fixed - // Set billing plan definitions - $paymentDefinition = new PaymentDefinition(); - $paymentDefinition->setName( 'Regular Payments' ) - ->setType( 'REGULAR' ) - ->setFrequency( $inputs['payment_frequency'] ) - ->setFrequencyInterval( $inputs['payment_interval'] ) - ->setCycles( $inputs['payment_cycles'] )//cycle 0 - ->setAmount( new Currency( array( - 'value' => $inputs['price'], - 'currency' => $inputs['currency'] - ) ) ); - // Set merchant preferences - $merchantPreferences = new MerchantPreferences(); - $merchantPreferences->setReturnUrl( $inputs['success_url'] ) - ->setCancelUrl( $inputs['failed_url'] ) - ->setAutoBillAmount( 'yes' ) - ->setInitialFailAmountAction( 'CONTINUE' ) - ->setMaxFailAttempts( '0' ); -// ->setSetupFee(new Currency(array('value' => 1, 'currency' => 'USD'))); - $plan->setPaymentDefinitions( array( $paymentDefinition ) ); - $plan->setMerchantPreferences( $merchantPreferences ); - $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), env( 'PAYPAL_CLIENT_SECRET', '' ) ); - //create plan - try { - $createdPlan = $plan->create( $apiContext ); + //---------------------------------------------------------- + public function executePayment($paymentId, $payerId) + { try { - $patch = new Patch(); - $value = new PayPalModel( '{"state":"ACTIVE"}' ); - $patch->setOp( 'replace' ) - ->setPath( '/' ) - ->setValue( $value ); - $patchRequest = new PatchRequest(); - $patchRequest->addPatch( $patch ); - $createdPlan->update( $patchRequest, $apiContext ); - $plan = Plan::get( $createdPlan->getId(), $apiContext ); - // Create new agreement - $agreement = new Agreement(); - $agreement->setName( 'Base Agreement' ) - ->setDescription( 'Basic Agreement' ) -// ->setShippingAddress( $shippingAddress ) - ->setStartDate( date( "Y-m-d\TH:i:s\Z", strtotime( 'tomorrow' ) ) ); - $_plan = new Plan(); - $_plan->setId( $plan->getId() ); - $agreement->setPlan( $_plan ); - // Add payer type - $payer = new Payer(); - $payer->setPaymentMethod( 'paypal' ); - $agreement->setPayer( $payer ); -// Adding shipping details - // Create agreement - $agreement = $agreement->create( $apiContext ); - // Extract approval URL to redirect user - $approvalUrl = $agreement->getApprovalLink(); - $response['status'] = 'success'; - $response['data'] = $approvalUrl; - $response['messages'][] = 'Redirecting you to Paypal'; - + $payment = \PayPal\Api\Payment::get($paymentId, $this->apiContext); + $execution = new \PayPal\Api\PaymentExecution(); + $execution->setPayerId($payerId); + $result = $payment->execute($execution, $this->apiContext); + $response = []; + $response['status'] = 'success'; + $response['data'] = $result->toArray(); return $response; - // Output plan id -// echo $plan->getId(); - } catch ( PayPal\Exception\PayPalConnectionException $ex ) { - $response['status'] = 'failed'; - $response['errors'][] = $ex->getData(); - + } catch (\PayPal\Exception\PayPalConnectionException $ex) { + $response = []; + $response['status'] = 'failed'; + $response['errors'] = $ex->getData(); return $response; -// die($ex); - } catch ( \Exception $ex ) { - $response['status'] = 'failed'; - $response['errors'][] = $ex; - + } catch (\Exception $ex) { + $response = []; + $response['status'] = 'failed'; + $response['errors'] = $ex->getMessage(); return $response; } - } catch ( PayPal\Exception\PayPalConnectionException $ex ) { - $response['status'] = 'failed'; - $response['errors'][] = $ex->getData(); - - return $response; - } catch ( \Exception $ex ) { - $response['status'] = 'failed'; - $response['errors'][] = $ex; - - return $response; } -// $payment_defination = - $response['status'] = 'success'; -// $response['data']['redirect_url'] = $payment->getApprovalLink(); - $response['messages'][] = 'Redirecting you to Paypal'; - - return $response; -} - - //---------------------------------------------------- + //---------------------------------------------------------- public function getApiContext( $clientId, $clientSecret ) { // #### SDK configuration // Register the sdk_config.ini file in current directory @@ -475,7 +205,7 @@ public function getApiContext( $clientId, $clientSecret ) { // based configuration $apiContext->setConfig( array( - 'mode' => env( 'PAYPAL_MODE' ), + 'mode' => $this->mode, 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'DEBUG', @@ -494,521 +224,4 @@ public function getApiContext( $clientId, $clientSecret ) { return $apiContext; } //---------------------------------------------------- - //----------------------------------------------------------------- -// public function executePayment( Request $request ) { -// $response = []; -// if ( $request->has( 'paymentId' ) && $request->has( 'PayerID' ) ) { -// -// $paymentId = $request->paymentId; -// $payerId = $request->PayerID; -// $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), -// env( 'PAYPAL_CLIENT_SECRET', '' ) ); -// $payment = Payment::get( $paymentId, $apiContext ); -// $execution = new PaymentExecution(); -// $execution->setPayerId( $payerId ); -// try { -// $result = $payment->execute( $execution, $apiContext ); -// $response['status'] = 'success'; -// $response['data'] = $paymentId; -// -// return $response; -// } catch ( \Exception $e ) { -// -// $response['status'] = 'failed'; -// $response['errors'][] = $e->getMessage(); -// -// return $response; -// } -// } -// -// $response['status'] = 'failed'; -// $response['errors'][] = 'Something went wrong. No Payment Id is received.'; -// -// return $response; -// } - - //----------------------------------------------------------------- - public function executePlan( Request $request ) { - - if ( isset( $_GET['token'] ) ) { - $token = $request['token']; - $agreement = new \PayPal\Api\Agreement(); - try { - $apiContext = $this->getApiContext( env( 'PAYPAL_CLIENT_ID', '' ), - env( 'PAYPAL_CLIENT_SECRET', '' ) ); - // Execute agreement - $payment = $agreement->execute( $token, $apiContext ); - $response['status'] = 'success'; - $response['data'] = $agreement->getId(); - - return $response; - } catch ( PayPal\Exception\PayPalConnectionException $ex ) { - $response = []; - $response['status'] = 'failed'; - $response['errors'][] = $ex->getData(); - - return $response; -// die($ex); - } catch ( \Exception $ex ) { - $response = []; - $response['status'] = 'failed'; - $response['errors'][] = $ex->getData(); - - return $response; - } - } else { -// echo "user canceled agreement"; - $response = []; - $response['status'] = 'failed'; - $response['errors'][] = "User cancelled request"; - - return $response; - } - } - - //---------------------------------------------------- - public function setShippingAddress( $shippingAddress ) { - - $_shippingAddress = new ShippingAddress(); - if ( isset( $shippingAddress['line_one'] ) ) { - $_shippingAddress->setLine1( $shippingAddress['line_one'] ); - } else { - $response['status'] = 'failed'; - $response['errors'][] = 'Address Line 1 is required.'; - - return $response; - } - if ( isset( $shippingAddress['line_two'] ) ) { - $_shippingAddress->setLine2( $shippingAddress['line_two'] ); - } - if ( isset( $shippingAddress['city'] ) ) { - $_shippingAddress->setCity( $shippingAddress['city'] ); - } else { - $response['status'] = 'failed'; - $response['errors'][] = 'Address City is required.'; - - return $response; - } - if ( isset( $shippingAddress['zip'] ) ) { - $_shippingAddress->setPostalCode( $shippingAddress['zip'] ); - } else { - $response['status'] = 'failed'; - $response['errors'][] = 'Address Zip is required.'; - - return $response; - } - if ( isset( $shippingAddress['country'] ) ) { - $_shippingAddress->setCountryCode( $shippingAddress['country'] ); - } else { - $response['status'] = 'failed'; - $response['errors'][] = 'Address Country is required.'; - - return $response; - } - if ( isset( $shippingAddress['state'] ) ) { - $_shippingAddress->setCountryCode( $shippingAddress['state'] ); - } else { - $response['status'] = 'failed'; - $response['errors'][] = 'Address state is required.'; - - return $response; - } - if ( isset( $shippingAddress['mobile'] ) ) { - $_shippingAddress->setPhone( $shippingAddress['mobile'] ); - } - if ( isset( $shippingAddress['name'] ) ) { - $_shippingAddress->setRecipientName( $shippingAddress['name'] ); - } - $response['status'] = 'success'; - $response['data'] = $_shippingAddress; - - return $response; -// return $_shippingAddress; - } - //---------------------------------------------------------- - - public function subscription($customer, - $card, - $address, - $price_id, - $return_url) - { - - $validate = self::validation($customer, - $card, $address, $price_id, $return_url, null,true); - - if(isset($validate['status']) && $validate['status'] == 'failed') - { - return $validate; - } - - try{ - - $customer_inputs = [ - 'email' => $customer['email'], - 'name' => $customer['name'], - 'address' => $address - ]; - - $card['number'] = str_replace( - '-', '', $card['number'] - ); - - $token = Stripe::tokens()->create([ - 'card' => $card, - ]); - - $customer_inputs['source'] = $token['id']; - - $customer = Stripe::customers()->create($customer_inputs); - - $method_inputs = [ - "type" => 'card', - "card" => $card - ]; - - $payment_method = Stripe::paymentMethods()->create($method_inputs); - - $customer_iD = $customer['id']; - $payment_method_iD = $payment_method['id']; - - Stripe::paymentMethods()->attach($payment_method_iD, $customer_iD); - - $subscription = Stripe::subscriptions()->create( - $customer_iD, - [ - 'plan' => $price_id, - 'payment_behavior' => 'default_incomplete', - 'expand' => ['latest_invoice.payment_intent'], - ] - ); - - $invoice = Stripe::invoices()->find($subscription['latest_invoice']['id']); - - - $pa_intent = Stripe::paymentIntents()->confirm( - $invoice['payment_intent'], - [ - "return_url" => $return_url - ] - ); - - $response['status'] = 'success'; - $response['data'] = $pa_intent; - - - }catch(\Exception $e) - { - $response['status'] = 'failed'; - $response['errors'][] = $e->getMessage(); - } - - return $response; - - } - //---------------------------------------------------------- - - public function createProduct(Request $request) - { - $inputs = $request->all(); - - $rules = array( - 'name' => 'required', - 'description' => 'required' - ); - - $validator = \Validator::make( $inputs, $rules); - if ( $validator->fails() ) { - - $errors = errorsToArray($validator->errors()); - $response['status'] = 'failed'; - $response['errors'] = $errors; - return $response; - } - - try{ - - $product = Stripe::products()->create([ - 'name' => $inputs['name'], - 'description' => $inputs['description'], - 'type' => 'service' - ]); - - $response['status'] = 'success'; - $response['data'] = $product; - - }catch(\Exception $e) - { - $response['status'] = 'failed'; - $response['errors'][] = $e->getMessage(); - } - - return $response; - - } - //---------------------------------------------------------- - - public function createPrice(Request $request) - { - $inputs = $request->all(); - - $rules = array( - 'product_id' => 'required', - 'amount' => 'required', - 'currency' => 'required', - 'interval' => 'required' - ); - - $validator = \Validator::make( $inputs, $rules); - if ( $validator->fails() ) { - - $errors = errorsToArray($validator->errors()); - $response['status'] = 'failed'; - $response['errors'] = $errors; - return $response; - } - - try{ - - $product = Stripe::prices()->create([ - 'unit_amount' => $inputs['amount'], - 'currency' => $inputs['currency'], - 'product' => $inputs['product_id'], - 'recurring' => [ - 'interval' => $inputs['interval'] - ] - ]); - - $response['status'] = 'success'; - $response['data'] = $product; - - }catch(\Exception $e) - { - $response['status'] = 'failed'; - $response['errors'][] = $e->getMessage(); - } - - return $response; - - } - //---------------------------------------------------------- - - public function findProductByName($name) - { - - if(!$name){ - $response['status'] = 'failed'; - $response['errors'] = 'The name field is required.'; - return $response; - } - - try{ - - $product_val = null; - - $data = [ - 'active' => true - ]; - - $products = Stripe::products()->all($data); - - foreach ($products['data'] as $product){ - - if($product['name'] == $name){ - $product_val = $product; - } - - } - - if(!$product_val){ - $response['status'] = 'failed'; - $response['errors'][] = 'No Product Found'; - return $response; - } - - $response['status'] = 'success'; - $response['data'] = $product_val; - - - }catch(\Exception $e) - { - $response['status'] = 'failed'; - $response['errors'][] = $e->getMessage(); - } - - return $response; - - } - //---------------------------------------------------------- - - public function getProductPrice($product_id, $value = null, $by = 'amount') - { - - if(!$product_id){ - $response['status'] = 'failed'; - $response['errors'] = 'The product id field is required.'; - return $response; - } - - try{ - - $price_val = null; - - $data = [ - 'active' => true - ]; - - $prices = Stripe::prices()->all($data); - - foreach ($prices['data'] as $price){ - - if($price['product'] == $product_id){ - if($value && $by){ - - switch ($by) - { - //------------------------------------ - case 'amount': - - if($price['unit_amount'] == $value){ - $price_val = $price; - } - - break; - - //------------------------------------ - case 'currency': - - if($price[$by] == $value){ - $price_val = $price; - } - - break; - - //------------------------------------ - case 'interval': - - if($price['recurring'][$by] == $value){ - $price_val = $price; - } - - break; - //------------------------------------ - - } - - }else{ - $price_val = $price; - } - } - - } - - if(!$price_val){ - $response['status'] = 'failed'; - $response['errors'][] = 'No Price Found'; - return $response; - } - - $response['status'] = 'success'; - $response['data'] = $price_val; - - - }catch(\Exception $e) - { - $response['status'] = 'failed'; - $response['errors'][] = $e->getMessage(); - } - - return $response; - - } - //---------------------------------------------------------- - - //---------------------------------------------------------- - public static function validation($customer, - $card, - $address, - $price_id, - $return_url, - $package, - $is_subscription = false){ - - $rules = array( - 'name' => 'required', - 'email' => 'required|email:rfc,dns' - ); - - $validator = \Validator::make( $customer, $rules); - if ( $validator->fails() ) { - - $errors = errorsToArray($validator->errors()); - $response['status'] = 'failed'; - $response['errors'] = $errors; - return $response; - } - - $rules = array( - 'number' => 'required', - 'exp_month' => 'required', - 'exp_year' => 'required', - 'cvc' => 'required' - ); - - $validator = \Validator::make( $card, $rules); - if ( $validator->fails() ) { - - $errors = errorsToArray($validator->errors()); - $response['status'] = 'failed'; - $response['errors'] = $errors; - return $response; - } - - if(!$is_subscription && $package){ - $rules = array( - 'currency' => 'required', - 'amount' => 'required', - 'description' => 'required' - ); - - $validator = \Validator::make( $package, $rules); - if ( $validator->fails() ) { - - $errors = errorsToArray($validator->errors()); - $response['status'] = 'failed'; - $response['errors'] = $errors; - return $response; - } - } - - $rules = array( - 'line1' => 'required', - 'country' => 'required', - ); - - $validator = \Validator::make( $address, $rules); - if ( $validator->fails() ) { - - $errors = errorsToArray($validator->errors()); - $response['status'] = 'failed'; - $response['errors'] = $errors; - return $response; - } - - if($is_subscription && !$price_id){ - $response['status'] = 'failed'; - $response['errors'] = 'The price id field is required.'; - return $response; - } - - if(!$return_url){ - $response['status'] = 'failed'; - $response['errors'] = 'The return url field is required.'; - return $response; - } - - } - //---------------------------------------------------------- - - } From 8efbd01665799bdf588b619312c2a662d7f200c2 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Sat, 3 Dec 2022 16:13:16 +0530 Subject: [PATCH 09/26] Updated : ApiContext var removed --- Libraries/VaahPayPal.php | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/Libraries/VaahPayPal.php b/Libraries/VaahPayPal.php index d4225a8..31e7f3f 100644 --- a/Libraries/VaahPayPal.php +++ b/Libraries/VaahPayPal.php @@ -26,7 +26,6 @@ class VaahPayPal{ - private $apiContext; private $mode; private $client_id; private $client_secret; @@ -46,7 +45,6 @@ public function __construct( $this->client_secret = $client_secret; $this->return_url = $return_url; $this->cancel_url = $cancel_url; - $this->apiContext = $this->getApiContext($this->client_id, $this->client_secret); } //---------------------------------------------------------- @@ -112,7 +110,7 @@ public function pay($inputs){ //create payment with valid api context try { - $resp = $payment->create($this->apiContext); + $resp = $payment->create($this->getApiContext()); $approvalUrl = $resp->getApprovalLink(); //approval url $response = []; $response['status'] = 'success'; @@ -136,8 +134,8 @@ public function pay($inputs){ public function getUserInfo(){ //getting user details try { - $token = $this->apiContext->getCredential()->getAccessToken($this->apiContext); //get access token - $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $this->apiContext); + $token = $this->getApiContext()->getCredential()->getAccessToken($this->getApiContext()); //get access token + $user = OpenIdUserinfo::getUserinfo(['access_token' => $token], $this->getApiContext()); $response = []; $response['status'] = 'success'; $response['data'] = $user->toArray(); @@ -158,10 +156,10 @@ public function getUserInfo(){ public function executePayment($paymentId, $payerId) { try { - $payment = \PayPal\Api\Payment::get($paymentId, $this->apiContext); + $payment = \PayPal\Api\Payment::get($paymentId, $this->getApiContext()); $execution = new \PayPal\Api\PaymentExecution(); $execution->setPayerId($payerId); - $result = $payment->execute($execution, $this->apiContext); + $result = $payment->execute($execution, $this->getApiContext()); $response = []; $response['status'] = 'success'; $response['data'] = $result->toArray(); @@ -179,7 +177,7 @@ public function executePayment($paymentId, $payerId) } } //---------------------------------------------------------- - public function getApiContext( $clientId, $clientSecret ) { + private function getApiContext() { // #### SDK configuration // Register the sdk_config.ini file in current directory // as the configuration source. @@ -195,8 +193,8 @@ public function getApiContext( $clientId, $clientSecret ) { // developer.paypal.com $apiContext = new ApiContext( new OAuthTokenCredential( - $clientId, - $clientSecret + $this->client_id, + $this->client_secret ), ); From ba3cba55f8d7b340e835ece67a02c54ae446a492 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Sat, 3 Dec 2022 16:40:56 +0530 Subject: [PATCH 10/26] Added: VaahPayPal.md --- Libraries/VaahPaypal.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Libraries/VaahPaypal.md diff --git a/Libraries/VaahPaypal.md b/Libraries/VaahPaypal.md new file mode 100644 index 0000000..e69de29 From f2e591189b2221b16e2e5b748a130d079bceab51 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Sat, 3 Dec 2022 16:43:57 +0530 Subject: [PATCH 11/26] Updated: VaahPayPal.md --- Libraries/VaahPayPal.md | 77 +++++++++++++++++++++++++++++++++++++++++ Libraries/VaahPaypal.md | 0 2 files changed, 77 insertions(+) create mode 100644 Libraries/VaahPayPal.md delete mode 100644 Libraries/VaahPaypal.md diff --git a/Libraries/VaahPayPal.md b/Libraries/VaahPayPal.md new file mode 100644 index 0000000..c1a8609 --- /dev/null +++ b/Libraries/VaahPayPal.md @@ -0,0 +1,77 @@ +# VaahPaypal +> Small Laravel Helpers + +### Installation + +VaahPaypal provides to you a simple way to integrate Paypal in your Laravel application. + +### Dependencies +- [PayPal-PHP-SDK](https://github.com/paypal/PayPal-PHP-SDK) + +### Installation + +```shell script +composer require paypal/rest-api-sdk-php +``` + +[comment]: <> (Add Facade in `config/app.php`:) + +[comment]: <> (```php) + +[comment]: <> ('aliases' => [) + +[comment]: <> (...) + +[comment]: <> ('VaahStripe' => WebReinvent\VaahExtend\Facades\VaahStripe::class,) + +[comment]: <> (...) + +[comment]: <> (]) + +[comment]: <> (```) + +Add env configuration: +```env +PAYPAL_MODE=sandbox +PAYPAL_SANDBOX_CLIENT_ID=xxxxxxxxxxxxxxx +PAYPAL_SANDBOX_CLIENT_SECRET=xxxxxxxxxxxxx +``` + +Reference url: https://developer.paypal.com/api/rest/ + +### Methods + +- Paypal Create Order + +```php +//Initialize the VaahPaypal +$vaahPaypal = new VaahPayPal( + $client_id, + $client_secret, + $return_url, + $cancel_url, + ); +//Create Order +$vaahPaypal->pay([ + 'name' => 'Name', + 'amount' => 100, + 'currency' => USD, + 'description' => 'Description', + 'quantity' => 1, + ]); +``` + +- Execute Order +```php +//Initialize the VaahPaypal + $vaahPaypal = new VaahPayPal( + $client_id, + $client_secret, + $return_url, + $cancel_url, + ); + //Execute the order + $payment_id = 'xxxx'; + $payer_id = 'xxxx'; + $vaahPaypal->executePayment($payment_id, $payer_id); +``` diff --git a/Libraries/VaahPaypal.md b/Libraries/VaahPaypal.md deleted file mode 100644 index e69de29..0000000 From eaaeca3fc4c8f3db1271a360eb7fbfbfcb68f6d7 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi Date: Mon, 5 Dec 2022 14:12:52 +0530 Subject: [PATCH 12/26] Updated: VaahPaypal usage file --- Libraries/VaahPayPal.md | 90 ++++++++++++++++++++++++----------------- 1 file changed, 53 insertions(+), 37 deletions(-) diff --git a/Libraries/VaahPayPal.md b/Libraries/VaahPayPal.md index c1a8609..cf745ca 100644 --- a/Libraries/VaahPayPal.md +++ b/Libraries/VaahPayPal.md @@ -1,4 +1,4 @@ -# VaahPaypal +# VaahPayPal > Small Laravel Helpers ### Installation @@ -13,65 +13,81 @@ VaahPaypal provides to you a simple way to integrate Paypal in your Laravel appl ```shell script composer require paypal/rest-api-sdk-php ``` +### Add env variables: -[comment]: <> (Add Facade in `config/app.php`:) - -[comment]: <> (```php) - -[comment]: <> ('aliases' => [) - -[comment]: <> (...) - -[comment]: <> ('VaahStripe' => WebReinvent\VaahExtend\Facades\VaahStripe::class,) - -[comment]: <> (...) - -[comment]: <> (]) - -[comment]: <> (```) - -Add env configuration: +PayPal live and PayPal sandbox are two different environments for using the PayPal API. The live environment is the real PayPal network that processes actual payments, while the sandbox environment is a simulated test environment that allows developers to test their integration with the PayPal API without using real money. ```env +## For PayPal Sandbox PAYPAL_MODE=sandbox PAYPAL_SANDBOX_CLIENT_ID=xxxxxxxxxxxxxxx PAYPAL_SANDBOX_CLIENT_SECRET=xxxxxxxxxxxxx +## For PayPal Live +PAYPAL_MODE=live +PAYPAL_LIVE_CLIENT_ID=xxxxxxxxxxxxxxx +PAYPAL_LIVE_CLIENT_SECRET=xxxxxxxxxxxxx ``` +To get your PayPal sandbox client secret and client ID, you first need to create a PayPal developer account at https://developer.paypal.com/. Once you have created your account, you can log in and create a sandbox account. This will allow you to test your integration with the PayPal API without using real money. -Reference url: https://developer.paypal.com/api/rest/ +To create a sandbox account, log in to your developer account and click on the "Dashboard" tab. From there, click on the "Sandbox" tab and then click on the "Accounts" link. This will take you to the sandbox accounts page where you can create a new sandbox account. -### Methods +Once you have created a sandbox account, you can view its client ID and client secret by clicking on the account and then clicking on the "Profile" link. This will open the account's profile page, where you can find the client ID and client secret. +### Initialize VaahPaypal + ```php +//Initialize the VaahPaypal + $vaahPaypal = new VaahPayPal( + $client_id, //required + $client_secret, //required + $return_url, //optional [default: /api/vaah/paypal/execute] + $cancel_url, //optional [default: /api/vaah/paypal/cancel] + $mode //optional [default: sandbox] +); +``` +The PayPal cancel and return URLs are the URLs that PayPal will redirect the user to after they have completed or canceled a payment. These URLs are specified by the developer in the PayPal API call, and they can be used to redirect the user back to the app or website after the payment is complete. + +### Methods - Paypal Create Order ```php -//Initialize the VaahPaypal -$vaahPaypal = new VaahPayPal( - $client_id, - $client_secret, - $return_url, - $cancel_url, - ); -//Create Order $vaahPaypal->pay([ 'name' => 'Name', 'amount' => 100, - 'currency' => USD, + 'currency' => 'USD', 'description' => 'Description', 'quantity' => 1, ]); + +//success response + [ + 'status' => 'success'; + 'approval_url' = 'approval url'; + 'payment_id' = 'xxxxx'; + 'token' = 'EC-xxxxxxxx'; + ]; + + //error response + [ + 'status' => 'error'; + 'errors' = 'errors'; + ]; ``` - Execute Order ```php -//Initialize the VaahPaypal - $vaahPaypal = new VaahPayPal( - $client_id, - $client_secret, - $return_url, - $cancel_url, - ); - //Execute the order +//Execute the order $payment_id = 'xxxx'; $payer_id = 'xxxx'; $vaahPaypal->executePayment($payment_id, $payer_id); + +//success response + [ + 'status' => 'success'; + 'data' => 'data'; //array + ]; + //error response + [ + 'status' => 'error'; + 'errors' = 'errors'; + ]; ``` +Reference url: https://developer.paypal.com/api/rest/ From 83bda0398716a07c2d91737bf9eb0bf8b3d7263b Mon Sep 17 00:00:00 2001 From: Himanshu Rahi <114979061+we-himanshu-r001-v1@users.noreply.github.com> Date: Mon, 5 Dec 2022 15:42:54 +0530 Subject: [PATCH 13/26] Updated: VaaPayPal Readme --- Libraries/VaahPayPal.md | 73 ++++++++++++++++++++++++++++++----------- 1 file changed, 53 insertions(+), 20 deletions(-) diff --git a/Libraries/VaahPayPal.md b/Libraries/VaahPayPal.md index cf745ca..6082afc 100644 --- a/Libraries/VaahPayPal.md +++ b/Libraries/VaahPayPal.md @@ -15,7 +15,7 @@ composer require paypal/rest-api-sdk-php ``` ### Add env variables: -PayPal live and PayPal sandbox are two different environments for using the PayPal API. The live environment is the real PayPal network that processes actual payments, while the sandbox environment is a simulated test environment that allows developers to test their integration with the PayPal API without using real money. +`PayPal live` and `PayPal sandbox` are two different environments for using the PayPal API. The live environment is the real PayPal network that processes actual payments, while the sandbox environment is a simulated test environment that allows developers to test their integration with the PayPal API without using real money. ```env ## For PayPal Sandbox PAYPAL_MODE=sandbox @@ -26,28 +26,51 @@ PAYPAL_MODE=live PAYPAL_LIVE_CLIENT_ID=xxxxxxxxxxxxxxx PAYPAL_LIVE_CLIENT_SECRET=xxxxxxxxxxxxx ``` -To get your PayPal sandbox client secret and client ID, you first need to create a PayPal developer account at https://developer.paypal.com/. Once you have created your account, you can log in and create a sandbox account. This will allow you to test your integration with the PayPal API without using real money. +To obtain your PayPal sandbox client ID and client secret, you will need to complete the following steps: -To create a sandbox account, log in to your developer account and click on the "Dashboard" tab. From there, click on the "Sandbox" tab and then click on the "Accounts" link. This will take you to the sandbox accounts page where you can create a new sandbox account. - -Once you have created a sandbox account, you can view its client ID and client secret by clicking on the account and then clicking on the "Profile" link. This will open the account's profile page, where you can find the client ID and client secret. + 1. Visit the [PayPal Developer](https://developer.paypal.com/home) website and sign in to your account. + 2. Click on the `Sandbox > Accounts` option in the top menu. + 3. In the `Business` section, click on the `Create` button to create a + new sandbox business account. + 4. Enter the required information to create your account and click + `Create Account`. + 5. Once your account has been created, click on the `Profile` link next + to the account. + 6. On the next page, you will see your `sandbox client ID` and + `client secret`. Make sure to save these values, as you will need them to + authenticate your app with PayPal in the sandbox environment. ### Initialize VaahPaypal ```php //Initialize the VaahPaypal $vaahPaypal = new VaahPayPal( - $client_id, //required - $client_secret, //required - $return_url, //optional [default: /api/vaah/paypal/execute] - $cancel_url, //optional [default: /api/vaah/paypal/cancel] - $mode //optional [default: sandbox] + $client_id, + $client_secret, + $return_url, + $cancel_url, + $mode ); ``` -The PayPal cancel and return URLs are the URLs that PayPal will redirect the user to after they have completed or canceled a payment. These URLs are specified by the developer in the PayPal API call, and they can be used to redirect the user back to the app or website after the payment is complete. +| Name | Description | Required | Default | +|--|--|--|--| +| client_id | PayPal Live/Sandbox client id| Yes +| client_secret| PayPal Live/Sandbox client_secret| Yes +| return_ url| redirect the user to after they have completed a payment.| No | /api/vaah/paypal/execute +| cancel_url | redirect the user to after they have canceled a payment. | No| /api/vaah/paypal/cancel| +| mode | environments for managing payments | No | sandbox ### Methods - Paypal Create Order +|Name| Required | Type | +|--|--|--| +| name | yes | String | +| quantity| yes | String +| amount| yes | String +| description| yes | String +| currency | yes | String | +|shipping | No | Integer +|tax| No | Integer ```php $vaahPaypal->pay([ 'name' => 'Name', @@ -56,35 +79,45 @@ $vaahPaypal->pay([ 'description' => 'Description', 'quantity' => 1, ]); + ``` -//success response +**Success response** + ```php [ 'status' => 'success'; 'approval_url' = 'approval url'; 'payment_id' = 'xxxxx'; 'token' = 'EC-xxxxxxxx'; ]; - - //error response - [ + ``` + **Error Response** + ```php + [ 'status' => 'error'; 'errors' = 'errors'; ]; -``` + ``` + - Execute Order -- Execute Order +|Name| Required +|--|--| +| payment_id | yes | +| payer_id | yes | ```php -//Execute the order $payment_id = 'xxxx'; $payer_id = 'xxxx'; $vaahPaypal->executePayment($payment_id, $payer_id); + ``` -//success response +**Success response** +```php [ 'status' => 'success'; 'data' => 'data'; //array ]; - //error response + ``` + **Error response** + ```php [ 'status' => 'error'; 'errors' = 'errors'; From 31cf4d4e763f2e527ae659b8c26add466dcb8506 Mon Sep 17 00:00:00 2001 From: Himanshu Rahi <114979061+we-himanshu-r001-v1@users.noreply.github.com> Date: Mon, 5 Dec 2022 16:24:57 +0530 Subject: [PATCH 14/26] Updated: VaahPayPal Readme --- Libraries/VaahPayPal.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Libraries/VaahPayPal.md b/Libraries/VaahPayPal.md index 6082afc..783a6c6 100644 --- a/Libraries/VaahPayPal.md +++ b/Libraries/VaahPayPal.md @@ -32,11 +32,10 @@ To obtain your PayPal sandbox client ID and client secret, you will need to comp 2. Click on the `Sandbox > Accounts` option in the top menu. 3. In the `Business` section, click on the `Create` button to create a new sandbox business account. - 4. Enter the required information to create your account and click - `Create Account`. - 5. Once your account has been created, click on the `Profile` link next + 4. Enter the required information to create your account and click `Create Account`. + 5. Once your account has been created, click on the `Profile` link next to the account. - 6. On the next page, you will see your `sandbox client ID` and + 6. On the next page, you will see your `sandbox client ID` and `client secret`. Make sure to save these values, as you will need them to authenticate your app with PayPal in the sandbox environment. From 4afc5cc626130d49808255f93da247be23f219fa Mon Sep 17 00:00:00 2001 From: Himanshu Rahi <114979061+we-himanshu-r001-v1@users.noreply.github.com> Date: Mon, 5 Dec 2022 16:28:58 +0530 Subject: [PATCH 15/26] Updated: VaahPayPal Readme --- Libraries/VaahPayPal.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Libraries/VaahPayPal.md b/Libraries/VaahPayPal.md index 783a6c6..5242896 100644 --- a/Libraries/VaahPayPal.md +++ b/Libraries/VaahPayPal.md @@ -92,7 +92,7 @@ $vaahPaypal->pay([ **Error Response** ```php [ - 'status' => 'error'; + 'status' => 'failed'; 'errors' = 'errors'; ]; ``` @@ -118,7 +118,7 @@ $vaahPaypal->pay([ **Error response** ```php [ - 'status' => 'error'; + 'status' => 'failed'; 'errors' = 'errors'; ]; ``` From 92535b1e6671e98478da66978e529956989ddd71 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Tue, 4 Jul 2023 19:58:44 +0530 Subject: [PATCH 16/26] fixed: imap issue --- Libraries/VaahAjax.php | 33 ++++++++++++++++++++++++++++++++- Libraries/VaahImap.php | 6 +++--- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/Libraries/VaahAjax.php b/Libraries/VaahAjax.php index 05ebff9..befdbc3 100644 --- a/Libraries/VaahAjax.php +++ b/Libraries/VaahAjax.php @@ -14,7 +14,38 @@ public function __construct() $this->ajax = new Client(); } //------------------------------------------------ - public function post($url, $params=null, $headers = null) + public function get($url, $query=null, $headers = null): array + { + $data = null; + + if(!is_null($query)) + { + $data['query'] = $query; + } + if(!is_null($headers)) + { + $data['headers'] = $headers; + } + try{ + $res = $this->ajax->request('GET', $url, $data); + $response = [ + 'status' => 'success', + 'data' => [ + 'status_code' => $res->getStatusCode(), + 'body' => $res->getBody(), + 'content' => $res->getBody()->getContents(), + ] + ]; + }catch(\Exception $e) + { + $response['status'] = 'failed'; + $response['errors'] = [$e->getMessage()]; + + } + return $response; + } + //------------------------------------------------ + public function post($url, $params=null, $headers = null): array { $data = null; diff --git a/Libraries/VaahImap.php b/Libraries/VaahImap.php index 6eab815..188a5d5 100644 --- a/Libraries/VaahImap.php +++ b/Libraries/VaahImap.php @@ -167,15 +167,15 @@ function getMail($uid) $data['date_time'] = $mail->date; - $data['subject'] = $mail->subject; + $data['subject'] = mb_convert_encoding($mail->subject, "UTF-8", "auto"); if(!isset($data['subject']) || $data['subject'] == "") { $data['subject'] = "(no subject)"; } - $data['message_html'] = $mail->textHtml; - $data['message_plain'] = $mail->textPlain; + $data['message_html'] = mb_convert_encoding($mail->textHtml, "UTF-8", "auto"); + $data['message_plain'] = mb_convert_encoding($mail->textPlain, "UTF-8", "auto"); $data['has_attachments'] = null; From 46ae80521395d182998838edcee02e900d4e1530 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Wed, 5 Jul 2023 20:18:02 +0530 Subject: [PATCH 17/26] updated: library --- Libraries/VaahImap.php | 60 +++++++++++++++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 13 deletions(-) diff --git a/Libraries/VaahImap.php b/Libraries/VaahImap.php index 188a5d5..04d94ac 100644 --- a/Libraries/VaahImap.php +++ b/Libraries/VaahImap.php @@ -61,7 +61,7 @@ function test(): array return $response; } //---------------------------------------------------------- - function connect($search_by='SINCE', $search_value=null) + function connect() { $response = $this->test(); @@ -71,10 +71,6 @@ function connect($search_by='SINCE', $search_value=null) return $response; } - if($search_by=='SINCE' && !$search_value){ - $search_value = date('d F Y'); - } - $this->imap = new \PhpImap\Mailbox( $this->mailbox, $this->username, @@ -88,6 +84,17 @@ function connect($search_by='SINCE', $search_value=null) $this->imap->setAttachmentsIgnore(true); } + return $this->imap; + } + //---------------------------------------------------------- + function searchMailBox($search_by='UNSEEN', $search_value=null){ + + $this->connect(); + + if($search_by=='SINCE' && !$search_value){ + $search_value = date('d F Y'); + } + try { if($search_by == 'SINCE') { @@ -97,6 +104,21 @@ function connect($search_by='SINCE', $search_value=null) } else{ $this->mail_uids = $this->searchMailBox('UNSEEN', SE_UID); } + + if(count($this->mail_uids) < 1) { + $response = [ + 'status' => "success", + 'data' => [], + 'messages' => ['Mailbox is empty'], + ]; + return $response; + } + + return [ + 'status' => "success", + 'data' => $this->mail_uids + ]; + } catch(\PhpImap\ConnectionException $ex) { $response = [ @@ -107,21 +129,30 @@ function connect($search_by='SINCE', $search_value=null) } - if(count($this->mail_uids) < 1) { - $response = [ - 'status' => "success", - 'data' => [], - 'messages' => ['Mailbox is empty'], - ]; - return $response; + + } + //---------------------------------------------------------- + function getMailUids($search_by='SINCE', $search_value=null) + { + + $connect = $this->searchMailBox($search_by, $search_value); + + if(isset($connect['status']) && $connect['status'] == 'failed') + { + return $connect; } + $response = [ + 'status' => "success", + 'data' => $this->mail_uids, + ]; + return $response; } //---------------------------------------------------------- function getMails($search_by='SINCE', $search_value=null) { - $connect = $this->connect($search_by, $search_value); + $connect = $this->searchMailBox($search_by, $search_value); if(isset($connect['status']) && $connect['status'] == 'failed') { @@ -155,6 +186,9 @@ function getMails($search_by='SINCE', $search_value=null) //---------------------------------------------------------- function getMail($uid) { + + $this->connect(); + $mail = $this->imap->getMail($uid); $data['mail_uid'] = $uid; From 282a9bc210de877e809a0b9dfb35ea92c45a475c Mon Sep 17 00:00:00 2001 From: Pradeep Date: Thu, 6 Jul 2023 00:12:19 +0530 Subject: [PATCH 18/26] updated: version --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 77f14b8..1d302ef 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "webreinvent/vaahextend", "description": "Quickly adaptable helpers to extend VaahCMS", "keywords": ["vaahcms", "laravel"], - "version": "0.0.5", + "version": "1.0.0", "homepage": "https://www.webreinvent.com", "license": "MIT", "authors": [ From 19e72c07f30f833682d373cb6e4d3b83abd264a8 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Thu, 6 Jul 2023 00:13:07 +0530 Subject: [PATCH 19/26] updated: version --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 1d302ef..00ab58c 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "webreinvent/vaahextend", "description": "Quickly adaptable helpers to extend VaahCMS", "keywords": ["vaahcms", "laravel"], - "version": "1.0.0", + "version": "1.0.1", "homepage": "https://www.webreinvent.com", "license": "MIT", "authors": [ From 65657c149715ed2b71d652bce6a546237c79d607 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Tue, 11 Jul 2023 19:17:37 +0530 Subject: [PATCH 20/26] added: mark as read and unread --- Libraries/VaahImap.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Libraries/VaahImap.php b/Libraries/VaahImap.php index 04d94ac..0167106 100644 --- a/Libraries/VaahImap.php +++ b/Libraries/VaahImap.php @@ -345,7 +345,14 @@ function getBcc($mail) } //---------------------------------------------------------- + function markAsRead($uid){ + return $this->imap->markMailAsRead($uid); + } + //---------------------------------------------------------- + function markMailAsUnread($uid){ + return $this->imap->markMailAsUnread($uid); + } //---------------------------------------------------------- //---------------------------------------------------------- } From 2decef77a5aba1242e70cdab9c1a846707c16975 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Tue, 11 Jul 2023 19:59:52 +0530 Subject: [PATCH 21/26] fixed: issue --- Libraries/VaahImap.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Libraries/VaahImap.php b/Libraries/VaahImap.php index 0167106..f4c75f9 100644 --- a/Libraries/VaahImap.php +++ b/Libraries/VaahImap.php @@ -346,11 +346,13 @@ function getBcc($mail) //---------------------------------------------------------- function markAsRead($uid){ + $this->connect(); return $this->imap->markMailAsRead($uid); } //---------------------------------------------------------- function markMailAsUnread($uid){ + $this->connect(); return $this->imap->markMailAsUnread($uid); } //---------------------------------------------------------- From 8ce57b6a432f6780257cf9eaf17f33fb9ed5241f Mon Sep 17 00:00:00 2001 From: Pradeep Date: Wed, 12 Jul 2023 15:13:19 +0530 Subject: [PATCH 22/26] fixed: syncing method --- Libraries/VaahImap.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Libraries/VaahImap.php b/Libraries/VaahImap.php index f4c75f9..1f33358 100644 --- a/Libraries/VaahImap.php +++ b/Libraries/VaahImap.php @@ -91,7 +91,8 @@ function searchMailBox($search_by='UNSEEN', $search_value=null){ $this->connect(); - if($search_by=='SINCE' && !$search_value){ + if($search_by === 'SINCE' && is_null($search_value)) + { $search_value = date('d F Y'); } @@ -132,7 +133,7 @@ function searchMailBox($search_by='UNSEEN', $search_value=null){ } //---------------------------------------------------------- - function getMailUids($search_by='SINCE', $search_value=null) + function getMailUids($search_by='UNSEEN', $search_value=null) { $connect = $this->searchMailBox($search_by, $search_value); From 0a58f9ac649e46f212b2c3b34e426370e49410c2 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Thu, 27 Jul 2023 02:11:28 +0530 Subject: [PATCH 23/26] added: VaahApollo --- Libraries/VaahApollo.php | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Libraries/VaahApollo.php diff --git a/Libraries/VaahApollo.php b/Libraries/VaahApollo.php new file mode 100644 index 0000000..b944b34 --- /dev/null +++ b/Libraries/VaahApollo.php @@ -0,0 +1,40 @@ +api_base_url = $api_base_url; + $this->api_key = $api_key; + } + //---------------------------------------------------------- + + public function getOrganizations($inputs ) + { + $url = $this->api_base_url."organizations/enrich"; + $ajax = new VaahAjax(); + $headers = []; + $inputs['api_key'] = $this->api_key; + + $res = $ajax->post($url, $inputs, $headers); + + unset($inputs['api_key']); + + $response['request'] = $inputs; + $response['response'] = $res; + + return $response; + } + //---------------------------------------------------------- + + +} From b72ca121285e7ccd88c1e2de864038af9c15d599 Mon Sep 17 00:00:00 2001 From: Pradeep Date: Wed, 23 Aug 2023 20:02:05 +0530 Subject: [PATCH 24/26] added: apollo method --- Libraries/VaahApollo.php | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Libraries/VaahApollo.php b/Libraries/VaahApollo.php index b944b34..2214b72 100644 --- a/Libraries/VaahApollo.php +++ b/Libraries/VaahApollo.php @@ -35,6 +35,40 @@ public function getOrganizations($inputs ) return $response; } //---------------------------------------------------------- + public function getPeople($inputs ) + { + $url = $this->api_base_url."mixed_people/search"; + $ajax = new VaahAjax(); + $headers = [ + 'Content-Type' => 'application/json' + ]; + + $inputs['api_key'] = $this->api_key; + + if(isset($inputs['domains']) + && is_array($inputs['domains']) + && count($inputs['domains']) > 0) + { + $inputs['q_organization_domains'] = implode('\n', $inputs['domains']); + } + + /* + * person_titles variable accept query string like + * person_titles[]=ceo&person_titles[]=cto + * which is not equal to php array, hence we have to convert it + */ + $apollo_inputs = http_build_query($inputs); + $apollo_inputs = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $apollo_inputs); + $res = $ajax->get($url, $apollo_inputs, $headers); + + unset($inputs['api_key']); + + $response['request'] = $inputs; + $response['response'] = $res; + + return $response; + } + //---------------------------------------------------------- } From a30ece062b25bfe1cf9d93dd1f5f9a9fd7669a5c Mon Sep 17 00:00:00 2001 From: Vineet Kumar Date: Tue, 26 Sep 2023 11:19:23 +0530 Subject: [PATCH 25/26] Updated: getPeople method --- Libraries/VaahApollo.php | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/Libraries/VaahApollo.php b/Libraries/VaahApollo.php index 2214b72..7d2d043 100644 --- a/Libraries/VaahApollo.php +++ b/Libraries/VaahApollo.php @@ -35,9 +35,11 @@ public function getOrganizations($inputs ) return $response; } //---------------------------------------------------------- - public function getPeople($inputs ) + public function getPeople($inputs) { + $url = $this->api_base_url."mixed_people/search"; + $ajax = new VaahAjax(); $headers = [ 'Content-Type' => 'application/json' @@ -45,24 +47,27 @@ public function getPeople($inputs ) $inputs['api_key'] = $this->api_key; - if(isset($inputs['domains']) - && is_array($inputs['domains']) - && count($inputs['domains']) > 0) - { - $inputs['q_organization_domains'] = implode('\n', $inputs['domains']); + if(isset($inputs['domains'])){ + if(is_array($inputs['domains']) && count($inputs['domains']) > 0){ + $inputs['q_organization_domains'] = implode("\n", $inputs['domains']); + }else if(is_string($inputs['domains'])){ + $inputs['q_organization_domains'] = preg_replace('/^www\./', '', $inputs['domains']); + } } + /* * person_titles variable accept query string like * person_titles[]=ceo&person_titles[]=cto * which is not equal to php array, hence we have to convert it */ + $apollo_inputs = http_build_query($inputs); $apollo_inputs = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $apollo_inputs); + $res = $ajax->get($url, $apollo_inputs, $headers); unset($inputs['api_key']); - $response['request'] = $inputs; $response['response'] = $res; From a78cf1516dce10a4470b212089ab2e13e49fc28a Mon Sep 17 00:00:00 2001 From: Vineet Kumar Date: Thu, 18 Apr 2024 15:40:00 +0530 Subject: [PATCH 26/26] Added: getMailAttachments function --- Libraries/VaahImap.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Libraries/VaahImap.php b/Libraries/VaahImap.php index 1f33358..164c0d5 100644 --- a/Libraries/VaahImap.php +++ b/Libraries/VaahImap.php @@ -357,5 +357,10 @@ function markMailAsUnread($uid){ return $this->imap->markMailAsUnread($uid); } //---------------------------------------------------------- + function getMailAttachments($mail_uid){ + $this->connect(); + $mail = $this->imap->getMail($mail_uid); + return $mail->getAttachments(); + } //---------------------------------------------------------- }