Updating an order value with the PayPal PHP SDK - php

OK, I've been banging my head against this for a few days now. I'm building a payment process into a PHP application which will allow for upselling products after a customer approves a payment.
I can get the payment charged to the customer without an issue, but if they select any kind of upsell product which requires the order value to change, then I get errors even though it is following to the letter what was in the documentation I could find...
Below is the test function I'm using, this is the function which is called when the user is redirected back to the website AFTER approving the payment.
public function confirmOrder($payer_id, $payment_id, $incentives = false){
//GET PAYMENT
$payment = Payment::get($payment_id, $this->apiContext);
//CREATE EXECUTION WITH PAYER ID
$execution = new PaymentExecution();
$execution->setPayerId($payer_id);
//APPLY PAYMENT AMOUNT - Original amount was 7.00
$amount = new Amount();
$amount = $amount->setCurrency('GBP')->setTotal('8.00');
//PATCH REPLACE
$patchReplace = new Patch();
$patchReplace = $patchReplace->setOp('replace')->setPath('/transactions/0/amount')->setValue($amount);
//CREATE PATCH OBJECT
$patchRequest = new PatchRequest();
$patchRequest = $patchRequest->setPatches(array($patchReplace));
try {
$payment->update($patchRequest, $this->apiContext);
} catch (PayPalConnectionException $ex) {
return "PATCH ERROR: State(" . $payment->getState() . ") ".$ex->getData();
}
}
This isn't the final code I will use but right now I'm just trying to get an order updated before I build in more of the logic. This code gives me the following error:
PATCH ERROR: State(created) {"name":"PAYMENT_STATE_INVALID","message":"This request is invalid due to the current state of the payment","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_STATE_INVALID","debug_id":"9caacdc1d652b"}
You can see I'm outputting the getState() which is coming back as 'created' which would normally be fine for updating in everything I can find but it is still failing.
Does anyone else have experience with the PayPal PHP SDK and could help point me in the right direction?

In PayPal, once the user has approved the payment from the consent screen, the amount cannot be changed, as you can understand the user agreed to pay only the amount he/she saw on the consent screen. Modifying the amount after user approves it, is not allowed, and that's why you are seeing that state exception, as the state is already approved.
Anyway, looking at your scenario, I think you might be interested in either creating order, or capture, instead of sale.
Also, in our PayPal-PHP-SDK, there are a lot of interesting documents that could help you understand PHP-SDK better. We also provide a lot of runnable samples, that you could setup in your local machine, by one command only.

Related

Applying a Paypal Web Pofile disables "Check out as a Guest"

I am trying to create a paypal payment page, but for some reason when I try to add a custom web profile to the payment the option of checking out as a guest suddenly disappears.
First I am creating the web profile this way:
$flowConfig = new FlowConfig();
$flowConfig
->setLandingPageType("billing")
->setBankTxnPendingUrl("...");
$presentation = new Presentation();
$presentation
->setLogoImage("...")
->setBrandName("...")
->setLocaleCode("...");
$inputFields = new InputFields();
$inputFields
->setNoShipping(1)
->setAddressOverride(0);
$webProfile = new WebProfile();
$webProfile->setName("PROFILE" . uniqid())
->setFlowConfig($flowConfig)
->setPresentation($presentation)
->setInputFields($inputFields);
$request = clone $webProfile;
try {
$createProfileResponse = $webProfile->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
...
}
$profileId = $createProfileResponse->getId();
Then, I have updated the payment code in this way
$paypalPayment = new PayPalPayment();
$paypalPayment->setIntent("sale");
$paypalPayment->setPayer($payer);
$paypalPayment->setRedirectUrls($redirectUrls);
$paypalPayment->setTransactions(array($transaction));
$paypalPayment->setExperienceProfileId($profileId);
The weird thing is that if I comment the last line I can perform payments as a guest without any issue. If, instead, I leave it this way, I get the customized page but the "Check out as a guest" button is replaced by "Create an account".
Do I really have to choose between having a customized checkout page and the possibility to perform payments without creating paypal accounts? Or am I missing something? I didn't find anything related to this issue in the documentation nor here in stackoverflow, and it seems at least strange!
Thank you
Are you using Express Checkout? It looks like recurring payments without a PayPal account are only compatible with Website Payments Pro accounts.
You can still create recurring payments with EC but they will need a PayPal account to accept them, no guest checkout allowed by the looks of it.
https://www.paypal-community.com/t5/Merchant-services-Archive/How-to-accept-recurring-payments-from-buyers-who-don-t-have-a/td-p/178232

Stripe create customer with coupon at subscription level

I'm using Stripe's php library to create a customer with a subscription that contains a coupon. I don't want to add the coupon at the customer level, I want to add it at the subscription level. The below code is what I'm currently using and according to their support, this should work, but it doesn't. I was hoping someone will be able to help.
$params = array(
'card'=>'SOME_TOKEN_FROM_JS_LIBRARY',
'plan'=>'valid_plan_id',
'coupon'=>'valid_coupon_id'
);
$c = Stripe_Customer::create($params);
if(!empty($params['coupon'])){
$c->updateSubscription(array(
'plan'=>$params['plan'],
'coupon'=>$params['coupon']
));
}
This successfully creates the customer and charges the card with the coupon applied.
Ended up going with the code below, it does what I want it to do. Also, the goal with the code below is to delete the customer if the charge fails for whatever reason, so I'm not left with customers that don't belong anywhere.
$_c = Stripe_Customer::create($params);
try{
$_c->subscriptions->create(array('plan'=>$plan, 'coupon'=>$coupon));
}catch(Exception $e){
$_c->delete();
throw new Exception($e->getMessage());
}
$c = Stripe_Customer::retrieve($_c->id); //to get the customer object with the latest data

Magento Order Emails

I am using magento 1.7.Can anyone help/advise on this??
Also using EPDQ Barclaycard module.
Everything seems ok with capturing payments, however when I go to checkout fill in all the details up to Payment Information select card type and hit continue, then place order a new order email has been sent but it hasnt been paid for yet!
Is there anyway that this can be prevented till payment has been captured via Barclaycard?
Have I missed something?
Thanks in advance
Magento sends email order confirmations as soon as the order is placed. If you are redirecting the user to a payment gateway after the order has been placed but not paid for you will need to modify your payment module to use magento's payment redirect setup to get it to ignore the confirmation email (See Mage_Checkout_Model_Type_Onepage class saveOrder() method).
You should see some code like;
/**
* a flag to set that there will be redirect to third party after confirmation
* eg: paypal standard ipn
*/
$redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
/**
* we only want to send to customer about new order when there is no redirect to third party
*/
if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
So this gives you a few options. Extend your payment module so that it sets the order place redirect url, but this might mess up your payment module depending on how it was coded or you could extend the above class into your own module (do not mod the core), override the saveOrder() method and check the payment method in the if statement shown above a bit like;
if (!$redirectUrl && $order->getPayment()->getMethod() != 'your_payment_method' && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
You would then to handle IPN notification to get it to send the email when a successful payment IPN is received, I would suggest you take a look at the PayPal Standard module that ships with Magento for some pointers as this is exactly how it works. I am surprised the EPDQ module you have does not work like this already, might be worth contacting them and highlighting the issue.

Magento sending SMS upon creating shipment

Banging my head for the last two days but unable to achieve this. Help!!
Whenever a shipment email is communicated I want to trigger a code which will send a SMS to the customer informing him/her that his order has been dispatched and also communicate the tracking number.
The code will be something like this:
<?php
$url = "http://www.abcde.in/binapi/pushsms.php?usr=xyz&pwd=abc&sndr=MEGYTR&ph=8888829554&text=This is test. MegaYtr&rpt=1";
$result = file_get_contents($url);
?>
Questions:
1) From where do I run this code?
2) How do I get additional info like Order Number, Customer Name, Grand Total & Tracking Number. I had done something similar for sending SMS when customer places order at that I used this code:
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_details = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$shipping_address_data = $order_details->getShippingAddress();
$first_name = $shipping_address_data['firstname'];
$telephone = $shipping_address_data['telephone'];
$amount_paid = $order_details->total_paid;
$message = 'Dear '.$first_name.' thank you for shopping at abc.com. Your order'.$this->getOrderId().' amounting to Rs.'.$amount_paid.'is being processed.';
echo '<b>'.$message.' Please check your email for further details.</b>';
I am using Magento Community 1.7.0.1.
try this
i would like to give you an simple solution without need of modifying core files.
for that you need to create an observer for SuccessAction below is the event that will trigger your code when an order is successfull
checkout_onepage_controller_success_action
this will help you in creating observer for the above event create observer using this
one more thing i would like to add is in the controller at location Mage/Checkout/OnepageController search for successAction, this is the Action which is processed on the succes of order. Here on line 240 if you comment $session->clear(); than you would not require to place order again and again, just by refreshing the page you can check your changes.
And lastly FYI above event will dispatch orderId by using that you can load the order object, for doing that the below is the code
//load order object
$_order = Mage::getModel('sales/order')->loadByIncrementId($order_id_from_observer);

Shopify API Partial Refund On Order Through Transaction Using PHP

(I'm a first time poster, so please forgive my lack of proper formatting, and if this question has already been answered in some form or fashion)
Issue: Shopify API - Partial Refund On Order Through Creation of A New Transaction(opposed to simply cancelling the order)
Reason: Give customer partial refund without cancelling the order
Problem: The Query Crashes at the point of sending the 'Create Transaction' into the shopify api, no errors, try and catch are not initiated, and the code after the query to shopify is ignored as well.
Shopify Developer API XML/JSON for Transactions:
http://api.shopify.com/transactions.html
Currently using Sandeepsheety's PHP API Code:
https://github.com/sandeepshetty/shopify.php/blob/master/README.md
<?php
//-------------------------------------------------------------------------------
//PHP Code Begins
//NOTE: [Does return correct values for the Order through GET through id=135264996 and,
// transaction GET data is verified as well - Test Order Total = $94.50 and,
// tested a few other orders ids with the same result.]
//-------------------------------------------------------------------------------
//Does connect and I have verified with a few GETS and even a couple cancellations
$shopify = shopify_api_client($SHOPIFY_STORE_URL, NULL, $SHOPIFY_API_KEY, $SHOPIFY_TOKEN, true);
//Based on Create Transactions: (POST /admin/orders/#{id}/transactions.json)
$jsonURL= "/admin/orders/135264996/transactions.json";
$query = $shopify('POST', $jsonURL, array('kind'='refund', 'amount'=10));
//NOTHING HAPPENS and Code Stops HERE
echo "Passed"; //IGNORED
?>
The Transaction API only supports 'capture' as the kind. The server is returning a 403 Forbidden, with text "Only capturing is currently supported".
shopify.php must not be handling that error properly but that is the issue you're running into.

Categories