Google Checkout PHP Submission Question - php

I have just started getting familiar with the Google Checkout API, but there's something I have a question about. On the Google Checkout Documentation, the only way of submitting the actual cart is via a button that is created via an echo call, like so echo $cart->CheckoutButtonCode("LARGE"); This however is not what I need. I want to manually submit my cart from my PHP script.
However, unlike the PayPal API, there appears to be no submit type function in the Google Checkout script. After some further research, I noticed that the HTML examples post their fields to https://sandbox.google.com/checkout/api/checkout/v2/checkout/Merchant/MERCHANT_ID_HERE.
How can I do this in PHP? I am using their official API. This is what I have done so far:
$merchant_id = $google_merchant_ID;
$merchant_key = $google_merchant_key;
if ($enable_Google_Sandbox == 1)
{
$server_type = "sandbox";
}
$currency = $currency_code;
$cart = new GoogleCart($merchant_id, $merchant_key, $server_type,
$currency);
$shop_cart = $_SESSION['cart'];
foreach ($shop_cart as $value)
{
$k_product = $value['Product'];
$k_quantity = $value['Quantity'];
$k_price = $value['Price'];
$k_orderID = $_SESSION['order_id'];
if (isset($_SESSION['Discount']))
{
$k_discount = $_SESSION['Discount'];
$k_price = $k_price - $k_discount;
}
$cart_item = new GoogleItem($k_product,
"Some Product",
$k_quantity,
$k_price);
$cart_item->SetMerchantItemId(generateProductID());
$cart->AddItem($cart_item);
}
// Specify <edit-cart-url>
$cart->SetEditCartUrl("http://192.168.100.100:8888/order.php?action=showCart");
// Specify "Return to xyz" link
$cart->SetContinueShoppingUrl("http://192.168.100.100:8888/store.php");
// Request buyer's phone number
$cart->SetRequestBuyerPhone(false);
There's no $cart->submitCart(); type function, so what do I do?

list($status, $error) = $cart->CheckoutServer2Server();
That should solve your problem. As you're using the PHP api, i can recommend the PHP demos. CheckoutServer2Server is demonstrated in this example (DigitalUsecase()). (digitalCart.php)
CheckoutServer2Server docs:
/**
* Submit a server-to-server request.
* Creates a GoogleRequest object (defined in googlerequest.php) and sends
* it to the Google Checkout server.
*
* more info:
* {#link http://code.google.com/apis/checkout/developer/index.html#alternate_technique}
*
* #return array with the returned http status code (200 if OK) in index 0
* and the redirect url returned by the server in index 1
*/

Related

getId() method is undefined in sandbox Square Checkout API script

I'm hoping to get a little assistance with something that is probably pretty basic -- I'm attempting to deploy the Square Checkout API with my website. I've been able to successfully install the SDK, and I've used it to successfully pull my sandbox location ID, to test it's function.
I've proceeded to build a page employing only the demo script on the Checkout API page, as seen below:
<?php
#Set the required includes globally
require_once '../config.php';
require INC_PATH . '/squareup/autoload.php';
/*
** Script for submitting payment information
** Utilizing Square API documentation at:
** https://docs.connect.squareup.com/payments/checkout/setup
*/
//Replace your access token and location ID
$accessToken = '<MY SANDBOX KEY>'; // Sandbox
$locationId = '<MY SANDBOX LOCATION ID>'; // Sandbox
// Create and configure a new API client object
$defaultApiConfig = new \SquareConnect\Configuration();
$defaultApiConfig->setAccessToken($accessToken);
$defaultApiClient = new \SquareConnect\ApiClient($defaultApiConfig);
$checkoutClient = new SquareConnect\Api\CheckoutApi($defaultApiClient);
//Create a Money object to represent the price of the line item.
$price = new \SquareConnect\Model\Money;
$price->setAmount(600);
$price->setCurrency('USD');
//Create the line item and set details
$book = new \SquareConnect\Model\CreateOrderRequestLineItem;
$book->setName('The Shining');
$book->setQuantity('2');
$book->setBasePriceMoney($price);
//Puts our line item object in an array called lineItems.
$lineItems = array();
array_push($lineItems, $book);
// Create an Order object using line items from above
$order = new \SquareConnect\Model\CreateOrderRequest();
$order->setIdempotencyKey(uniqid()); //uniqid() generates a random string.
//sets the lineItems array in the order object
$order->setLineItems($lineItems);
## STEP 2: Create a checkout object
$checkout = new \SquareConnect\Model\CreateCheckoutRequest();
$checkout->setIdempotencyKey(uniqid()); //uniqid() generates a random string.
$checkout->setOrder($order); //this is the order we created in the previous step
try {
$result = $checkoutClient->createCheckout(
$locationId,
$checkout
);
//Save the checkout ID for verifying transactions
$checkoutId = $result->getId();
//Get the checkout URL that opens the checkout page.
$checkoutUrl = $result->getCheckoutPageUrl();
print_r('Complete your transaction: ' + $checkoutUrl);
}
catch (Exception $e) {
echo 'Exception when calling CheckoutApi->createCheckout: ', $e->getMessage(), PHP_EOL;
}
I get a 500 error from my webserver when attempting to run this script through my browser, in my httpd error_log I get the following error message:
PHP Fatal error: Uncaught Error: Call to undefined method SquareConnect\\Model\\CreateCheckoutResponse::getId() in <LOCATION>:62\nStack trace:\n#0 {main}\n thrown in <LOCATION> on line 62
Any thoughts on why the getId() method is undefined? Thanks.
UPDATE
I commented out the function calls after the createCheckout() portion of the try{} block, and then ran a var_dump() on $result to make sure I was in fact getting some sort of response. I am getting back the expected result! So I KNOW the API/SDK is working now, I just can't figure out why the $result object is unable to accept the follow-up functions.
Revised try block:
try {
$result = $checkoutClient->createCheckout(
$locationId,
$checkout
);
/*
//Save the checkout ID for verifying transactions
$checkoutId = $result->getId();
//Get the checkout URL that opens the checkout page.
$checkoutUrl = $result->getCheckoutPageUrl();
print_r('Complete your transaction: ' + $checkoutUrl);
*/
}
catch (\Exception $e) {
echo 'Exception when calling CheckoutApi->createCheckout: ', $e->getMessage(), PHP_EOL;
}
var_dump($result); //test to see if any non-zero response to createCheckout() function.
Any thoughts based on this revision? -A
The CreateCheckoutResponse doesn't have the getId() function. It has getCheckout() and getErrors(). So you need to:
$checkoutId = $result->getCheckout()->getId();
Reference: https://github.com/square/connect-php-sdk/blob/master/docs/Model/CreateCheckoutResponse.md
Current Solution:
function objectToArray ($object) {
if(!is_object($object) && !is_array($object))
return $object;
return array_map('objectToArray', (array) $object);
}
$result_array = objectToArray($result);
echo '<pre>';
var_dump($result_array); //test to see if any non-zero response to createCheckout() function.
echo '</pre>';
Since I am getting a valid object back, and all I need to do is extract the ID and checkout URL's from the $result object, I used the function above to convert the object to an array, and from here I'll extract the information I need by key => Value pairing. It's ugly, and it doesn't solve why these post API-call functions included with the SDK aren't working, but it's meeting my immediate solution.
If anyone can tell me what actually happened that prevented the SDK function calls from being defined, I'd appreciate it.

Openfire: Add user with subscription status as "both"

I am facing issue when i add user using RestApi
include "vendor/autoload.php";
$api = new Gidkom\OpenFireRestApi\OpenFireRestApi;
$api->secret = "mySecretKey";
$api->host = "HostName";
$api->port = "9090";
$api->useSSL = false;
$api->plugin = "/plugins/restapi/v1"; // plugin
For adding user to Roster i am using following code
$jid="xyz#domainname";
//Add to roster
$data=$api->addToRoster("abc", $jid);
Which points to OpenFireRestApi.php which do have function named addToRoster
/**
* Adds to this OpenFire user's roster
*
* #param string $username Username
* #param string $jid JID
* #param string|false $name Name (Optional)
* #param int|false $subscription Subscription (Optional)
* #return json|false Json with data or error, or False when something went fully wrong
*/
public function addToRoster($username, $jid, $name=false, $subscription=false)
{
$endpoint = '/users/'.$username.'/roster';
return $this->doRequest('post', $endpoint, compact('jid','name','subscription'));
}
So I've used
$data=$api->addToRoster("abc", $jid,"DummyName",3);
Where 3 is subscription type as both = 3 which is mentioned.
But when i add user shows subscription type as none only.
UPDATE
I came to know about subscription plugin
So I've installed plugin configure it
Plugin itself says it will automatically subscribe both way.
Afterwards i've again tried with
$data=$api->addToRoster("abc", $jid);
Which aspects to be working but again subscriptions is none only.
Any Help would be appreciated.
There is problem with php-openfire-restapi classes
Need to change name of parameters
So do following changes :
//Add to roster
$username = "username in which you want to add roster";
$jid = "another users JID";
$nickname= "nick name of another user";
$subscription ="3";
$result = $api->addToRoster($username, $jid,$nickname,$subscription);
and change following line in /src/Gidkom/OpenFireRestApi/OpenFireRestApi.php file
public function addToRoster($username, $jid, $name=false, $subscription=false)
{
$nickname=$name;
$subscriptionType=$subscription;
$endpoint = '/users/'.$username.'/roster';
return $this->doRequest('post', $endpoint, compact('jid','nickname','subscriptionType'));
}
Here I have changed parameter names.
Good Luck.

Magento: change shipping method on existing order

I'm trying to change the shipping on an existing order in Magento. This works fine from the admin backend, even if it's quite the process since I have to manually update a lot of the order fields/attributes after I set the new shipping method on the shipping address object and recalculate the quote totals.
My problem is when running the same code on the frontend, it doesn't work at all, the quote collectTotals will revert any changes I've made in the shippingAddress, and I have no idea how to solve it or why it works from the backend.
This is how it looked:
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setShippingMethod('dynamicshipping_'.$shippingCode);
$shippingAddress->setCollectShippingRates(true);
$shippingAddress->collectShippingRates();
$quote->setUseCustomerBalance(1)->setTotalsCollectedFlag(false)->collectTotals()->save();
$order->setShippingHiddenTaxAmount($shippingAddress->getShippingHiddenTaxAmount());
$order->setBaseShippingHiddenTaxAmount($shippingAddress->getBaseShippingHiddenTaxAmount());
$order->setBaseShippingHiddenTaxAmnt($shippingAddress->getBaseShippingHiddenTaxAmnt());
$order->setShippingInclTax($shippingAddress->getShippingInclTax());
$order->setBaseShippingInclTax($shippingAddress->getBaseShippingInclTax());
$order->setShippingTaxAmount($shippingAddress->getShippingTaxAmount());
$order->setBaseShippingTaxAmount($shippingAddress->getBaseShippingTaxAmount());
$order->setShippingAmount($shippingAddress->getShippingAmount());
$order->setBaseShippingAmount($shippingAddress->getBaseShippingAmount());
$order->setShippingDiscountAmount($shippingAddress->getShippingDiscountAmount());
$order->setBaseShippingDiscountAmount($shippingAddress->getBaseShippingDiscountAmount());
$order->setGrandTotal($shippingAddress->getGrandTotal());
$order->setBaseGrandTotal($shippingAddress->getBaseGrandTotal());
$order->setShippingMethod('dynamicshipping_'.$shippingCode);
$order->setShippingDescription($shippingDescription);
$order->setServicePoint($servicePoint);
$order->save();
And as I said, that worked fine every time from the backend, but not when called from the frontend.
I've tried variations, such as this to try and eradicate any trace of the old shipping method, with no luck.
$quote->getShippingAddress()->removeAllShippingRates()
->setShippingMethod('dynamicshipping_'.$shippingCode)
->setShippingDescription($shippingDescription)
//->setBaseShippingAmount(0)
//->setBaseShippingTaxAmount(0)
//->setShippingTaxAmount(0)
//->setShippingInclTax(0)
->setCollectShippingRates(true)
//->unsetData('cached_items_all')
//->unsetData('cached_items_nominal')
//->unsetData('cached_items_nonnominal')
->collectShippingRates()
//->collectTotals()
->save();
It looks to me as if the quote is using an older/diffrent copy of the shipping address when I'm calling collectTotals, no matter what I do.
Any suggestions, or perhaps insight on how it's even possible that this works in the backend but not the frontend?
EDIT
After more debugging, I can see that the shipping does change both in frontend and backend. The problem is, the fee will only change when running this code through the backend. Very strange. It just refuses to update shipping fee.
Looks like I had some issues with an observer on collectTotals, which is the reason it worked in the backend where the event wasn't fired.
The complete code for reference, which I recently changed to use a more fail-safe method to copy all the fields back to the order.
/* #var $order Mage_Sales_Model_Order */
/* #var $quote Mage_Sales_Model_Quote */
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setShippingMethod('dynamicshipping_'.$shippingCode);
$shippingAddress->setShippingDescription($shippingDescription);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates();
$quote->collectTotals();
if ($this->updateMagentoOrder($order, $quote)) {
// here's where I check if we successfully updated the authorized
// amount at the payment gateway, before saving anything
// wrapping the payment update and save in a try-catch
$quote->save();
$order->save();
}
And using this method for updating all the order fields:
/**
* Updates a Magento order based on quote changes
* will not save anything, up to the caller.
* deleting items not supported.
*
* #param $order Mage_Sales_Model_Order
* #param $quote Mage_Sales_Model_Quote
* #return bool
*/
public function updateMagentoOrder($order, $quote) {
if (!$order instanceof Mage_Sales_Model_Order || !$quote instanceof Mage_Sales_Model_Quote) {
return false;
}
try {
$converter = Mage::getSingleton('sales/convert_quote');
$converter->toOrder($quote, $order);
foreach ($quote->getAllItems() as $quoteItem) {
$orderItem = $converter->itemToOrderItem($quoteItem);
$quoteItemId = $quoteItem->getId();
$origOrderItem = empty($quoteItemId) ? null : $order->getItemByQuoteItemId($quoteItemId);
if ($origOrderItem) {
$origOrderItem->addData($orderItem->getData());
} else {
if ($quoteItem->getParentItem()) {
$orderItem->setParentItem(
$order->getItemByQuoteItemId($quoteItem->getParentItem()->getId())
);
$orderItem->setParentItemId($quoteItem->getParentItemId());
}
$order->addItem($orderItem);
}
}
if ($shippingAddress = $quote->getShippingAddress()) {
$converter->addressToOrder($shippingAddress, $order);
}
} catch (Exception $e) {
Mage::logException($e);
return false;
}
return true;
}
For reference, the method above could loop $order->getAllItems() and do $orderItem->cancel()->delete(); on them first - but I won't support deleting items right now.
The cancel() part before deletion is so that the CatalogInventory module can restore stock. It's listening for the sales_order_item_cancel event.

Cant find 'cancel_return' option on paypal sandbox page, using codeigniter and paypal lib

I am trying to use paypal lib https://github.com/jersonandyworks/Paypal-Library-by-RomyBlack on my Codeigniter project.
I am able to navigate to paypal n pay for the product on sandbox, the problem is
There is no cancel_retun option on paypal.
There is no return url after the payment is completed
The below code is my controller code.
$this->load->library('paypal');
$config['business'] = 'QD8HYTTSE4M38';
$config['cpp_header_image'] = ''; //Image header url [750 pixels wide by 90 pixels high]
$config['return'] = 'main/viewAds/info.php';
//echo $config['return'];
$config['cancel_return'] = $this->config->base_url() .'main/viewAds/22';
$config['notify_url'] = $this->config->base_url() .'main/viewAds/30';
$config['production'] = FALSE; //Its false by default and will use sandbox
$config["invoice"] = '843843'; //The invoice id
$this->load->library('paypal',$config);
#$this->paypal->add(<name>,<price>,<quantity>[Default 1],<code>[Optional]);
$this->paypal->add('T-shirt',1,1); //First item
$this->paypal->pay(); //Proccess the payment
The below is the library
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* #package CodeIgniter
* #author Romaldy Minaya
* #copyright Copyright (c) 2011, PROTOS.
* #license GLP
* #since Version 1.0
* #version 1.0
*/
// ------------------------------------------------------------------------
/**
* Paypal Class
*
* #package CodeIgniter
* #subpackage Libraries
* #category Payment process
* #author Romaldy Minaya
*
// ------------------------------------------------------------------------
Documentation
This class let you make the payment procces based on paypal API,
effortless and easy.
*1)Use the same documentation about the vars from paypal page.
*2)Customize the payment procces as you desire.
*3)Build with love.
Implementation
*1)Copy this code in your controller's function
$config['business'] = 'demo#demo.com';
$config['cpp_header_image'] = ''; //Image header url [750 pixels wide by 90 pixels high]
$config['return'] = 'sucess.php';
$config['cancel_return'] = 'shopping.php';
$config['notify_url'] = 'process_payment.php'; //IPN Post
$config['production'] = TRUE; //Its false by default and will use sandbox
$config['discount_rate_cart'] = 20; //This means 20% discount
$config["invoice"] = '843843'; //The invoice id
$this->load->library('paypal',$config);
#$this->paypal->add(<name>,<price>,<quantity>[Default 1],<code>[Optional]);
$this->paypal->add('T-shirt',2.99,6); //First item
$this->paypal->add('Pants',40); //Second item
$this->paypal->add('Blowse',10,10,'B-199-26'); //Third item with code
$this->paypal->pay(); //Proccess the payment
The notify url is where paypal will POST the information of the payment so you
can save that POST directly into your DB and analize as you want.
With $config["invoice"] is how you identify a bill and you can compare,save or update
that value later on your DB.
For test porpuses i do recommend to save the entire POST into your DB and analize if
its working according to your needs before putting it in production mode. EX.
$received_post = print_r($this->input->post(),TRUE);
//Save that variable and analize.
Note: html reference page http://bit.ly/j4wRR
*/
class Paypal {
var $config = Array();
var $production_url = 'https://www.paypal.com/cgi-bin/webscr?';
var $sandbox_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?';
var $item = 1;
/**
* Constructor
*
* #param string
* #return void
*/
public function __construct($props = array())
{
$this->__initialize($props);
log_message('debug', "Paypal Class Initialized");
}
// --------------------------------------------------------------------
/**
* initialize Paypal preferences
*
* #access public
* #param array
* #return bool
*/
function __initialize($props = array())
{
#Account information
$config["business"] = 'QD8HYTTSE4M38'; //Account email or id
$config["cmd"] = '_cart'; //Do not modify
$config["production"] = FALSE;
#Custom variable here we send the billing code-->
$config["custom"] = '';
$config["invoice"] = ''; //Code to identify the bill
#API Configuration-->
$config["upload"] = '1'; //Do not modify
$config["currency_code"] = 'USD'; //http://bit.ly/anciiH
$config["disp_tot"] = 'Y';
#Page Layout -->
$config["cpp_header_image"] = ''; //Image header url [750 pixels wide by 90 pixels high]
$config["cpp_cart_border_color"] = '000'; //The HTML hex code for your principal identifying color
$config["no_note"] = 1; //[0,1] 0 show, 1 hide
#Payment Page Information -->
$config["return"] = ''; //The URL to which PayPal redirects buyers’ browser after they complete their payments.
$config["cancel_return"] = ''; //Specify a URL on your website that displays a “Payment Canceled†page.
$config["notify_url"] = ''; //The URL to which PayPal posts information about the payment (IPN)
$config["rm"] = '2'; //Leave this to get payment information
$config["lc"] = 'EN'; //Languaje [EN,ES]
#Shipping and Misc Information -->
$config["shipping"] = '';
$config["shipping2"] = '';
$config["handling"] = '';
$config["tax"] = '';
$config["discount_amount_cart"] = ''; //Discount amount [9.99]
$config["discount_rate_cart"] = ''; //Discount percentage [15]
#Customer Information -->
$config["first_name"] = '';
$config["last_name"] = '';
$config["address1"] = '';
$config["address2"] = '';
$config["city"] = '';
$config["state"] = '';
$config["zip"] = '';
$config["email"] = '';
$config["night_phone_a"] = '';
$config["night_phone_b"] = '';
$config["night_phone_c"] = '';
/*
* Convert array elements into class variables
*/
if (count($props) > 0)
{
foreach ($props as $key => $val)
{
$config[$key] = $val;
}
}
$this->config = $config;
}
// --------------------------------------------------------------------
/**
* Perform payment process
*
* #access public
* #param array
* #return void
*/
function pay(){
#Convert the array to url encode variables
$vars = http_build_query($this->config);
if($this->config['production'] == TRUE){
header('LOCATION:'.$this->production_url.$vars);
}else{
header('LOCATION:'.$this->sandbox_url.$vars);
}
}
// --------------------------------------------------------------------
/**
* Add a product to the list
*
* #access public
* #param array
* #return void
*/
function add($item_name = '',$item_amount = NULL,$item_qty = NULL,$item_number = NULL){
$this->config['item_name_'.$this->item] = $item_name;
$this->config['amount_'.$this->item] = $item_amount;
$this->config['quantity_'.$this->item] = $item_qty;
$this->config['item_number_'.$this->item] = $item_number;
$this->item++;
}
}
// END Paypal Class
/* End of file Paypal.php /
/ Location: ./application/libraries/Paypal.php */
This is the transaction page i get
I am expecting it to return to my web site but it just stays there.
Kindly advice me on what to do. Thanks.
This library you're using is apparently using PayPal Standard, which does not guarantee the user will be returned to your site.
You can enable Auto-Return from within your PayPal account profile, but still, if the user closes the browser or goes somewhere else on their prior to the redirect happening they won't make it there.
If you want to ensure you always get back to PayPal you'll need to switch to the Express Checkout API, which does guarantee that the user will end up back at your site. I have a PHP Class Library for PayPal that will make this very simple for you. That is my primary version that I continue to maintain, and it works with Composer so you can use that to autoload and make it available in CI.
Alternatively, I do have an old CI specific version of the library you might want to use instead. It's not far behind right now, but I'm not going to maintain it like I am the primary one.
Either way, you'll be working with SetExpressCheckout, GetExpressCheckoutDetails, and DoExpressCheckoutPayment.
I would also recommend you take a look at Instant Payment Notification (IPN). It will allow you to automate tasks in real-time based on transactions that hit your account regardless of whether or not the user makes it back to your site.

How do I call this function in CodeIgniter controller?

I've got this code, but I'm not sure I make it work:
/**
* Function: youtube data grabber
*
* #description :
* #param $ : video code, url type (embed/url)
* #return : data array
* #author : Mamun.
* #last -modified-by: Mamun.
*/
if (! function_exists('youtube_data_grabber'))
{
function youtube_data_grabber($video_code, $link_type = "embed")
{
if ($video_code != '')
{
if ($link_type == "embed")
{
$splited_data = explode("=",$video_code);
$video_unique_code = substr(strrchr($splited_data[4],"/"),1,-strlen(strrchr($splited_data[4],"&")));
}
else if ($link_type == "url")
{
$splited_data = explode("=",$video_code);
$video_unique_code = substr($splited_data[1],0,-strlen(strrchr($splited_data[1],"&")));
}
else
{
return;
}
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$video_unique_code;
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
return $sxml;
}
}
} // End Youtube Function
I'm not sure how to activate it is what I'm trying to say. I placed it in the controller and it's within a function for one of my pages. I don't have any syntax errors. I just don't know how to wake it up and make it work. I thought I could just put youtube_data_grabber('http://www.youtube.com/watch?v=LAcrFym10ZI', 'url'); but that didn't work.
I got the code from this blog, and I have the zend functionality working. I tested it earlier and had no errors. I'm just having trouble with this youtube part.
Any ideas?
That code should go in a helper or plugin not in the controller. The first part of the code on that page should be in your controller. The one you pasted is just an alternate version.
Save your code to application/helpers/youtube_helper.php, then in your controller go ahead and call $this->load->helper('youtube').
Only then will your youtube_data_grabber() function be available.

Categories