Skip to content

Instantly share code, notes, and snippets.

@DasRed
Created October 13, 2017 18:46
Show Gist options
  • Save DasRed/0d89cf28a95b177859797ad0e82cd840 to your computer and use it in GitHub Desktop.
Save DasRed/0d89cf28a95b177859797ad0e82cd840 to your computer and use it in GitHub Desktop.
Fixing WP Photo Seller Plugin Chartset Conversion to UTF8
<?php
class WPSPayPalStandard
{
protected $_log;
public function __construct()
{
$paypalUrl = WPSCommon::getPayPalUrl();
WPSCommon::log("Constructing PayPal Gateway for IPN using URL: $paypalUrl");
}
/**
* Save a PayPal IPN order from a Website Payments Pro cart sale.
*
* @param array $pp Urldecoded array of IPN key value pairs
*/
public function saveOrder($pp)
{
WPSCommon::log("WPSPayPalStandard::saveOrder got called");
global $wpdb;
$orderTable = WPSCommon::getTableName('orders');
// Make sure the transaction id is not already in the database
$sql = "SELECT * from $orderTable where trans_id=%s";
$sql = $wpdb->prepare($sql, $pp['txn_id']);
$row = $wpdb->get_row($sql);
if (!empty($row)) {
WPSCommon::log("WPSPayPalStandard::saveOrder. This transaction (" . $pp['txn_id'] . ") has already been processed.");
return $row->id;
}
$hasDigital = false;
// Calculate subtotal
$subtotal = 0;
$numCartItems = ($pp['num_cart_items'] > 0) ? $pp['num_cart_items'] : 1;
for ($i = 1; $i <= $numCartItems; $i++) {
// PayPal in not consistent in the way it passes back the item amounts
$amt = 0;
if (isset($pp['mc_gross' . $i])) {
$amt = $pp['mc_gross' . $i];
} elseif (isset($pp['mc_gross_' . $i])) {
$amt = $pp['mc_gross_' . $i];
}
$subtotal += $amt;
}
$statusOptions = WPSCommon::getOrderStatusOptions();
$status = $statusOptions[0];
$ouid = md5($pp['txn_id'] . $pp['address_street']);
// Parse custom value
$referrer = "";
$custom_info = $pp['custom'];
if (strpos($custom_info, '|') !== false) {
list($deliveryMethod, $referrer, $gfData, $coupon, $share_cart_discount, $cart_ref_id) = explode('|', $custom_info);
}
//Retrieve cart object
if (isset($cart_ref_id)) {
$cart_object = WPSCommon::retrieve_cart_object($cart_ref_id);
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Retrieved cart object to process: " . print_r($cart_object, true));
} else {
$cart_object = '';
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] WPSPayPalStandard: Paypal custom data returned nothing for cart object ref_id value");
}
if(!empty($cart_object)){
$subtotal = $cart_object->getSubTotal();
}
// Parse Gravity Forms ids
$gfIds = array();
if (!empty($gfData)) {
$forms = explode(',', $gfData);
foreach ($forms as $f) {
list($itemId, $formEntryId) = explode(':', $f);
$gfIds[$itemId] = $formEntryId;
}
}
// Look for discount amount
$discount = 0;
if (isset($pp['discount'])) {
$discount = $pp['discount'];
}
// Look for coupon code
$coupon_code = "none";
if (isset($coupon) && $coupon != "") {
$coupon_code = $coupon;
}
//Check for type of delivery method
if ($deliveryMethod == 'Pickup') {
$shipping_cost = 0;
} else {
$shipping_cost = isset($pp['mc_handling'])?$pp['mc_handling']:0;
}
$tax = isset($pp['tax'])?$pp['tax']:0;
$tax_included_in_price = $cart_object->getPriceIncTaxStatus();
$total = $cart_object->getCartGrandTotal();
$contact_ph = empty($pp['contact_phone'])?'':$pp['contact_phone'];
$data = array(
'bill_first_name' => $pp['address_name'],
'bill_address' => $pp['address_street'],
'bill_city' => $pp['address_city'],
'bill_state' => $pp['address_state'],
'bill_zip' => $pp['address_zip'],
'bill_country' => $pp['address_country'],
'ship_first_name' => $pp['address_name'],
'ship_address' => $pp['address_street'],
'ship_city' => $pp['address_city'],
'ship_state' => $pp['address_state'],
'ship_zip' => $pp['address_zip'],
'ship_country' => $pp['address_country'],
'shipping_method' => $deliveryMethod,
'email' => $pp['payer_email'],
'phone' => $contact_ph,
'shipping' => $shipping_cost,
'tax' => $tax,
'subtotal' => $subtotal,
'total' => $total,
'coupon' => $coupon_code,
'discount_amount' => $discount,
'trans_id' => $pp['txn_id'],
'ordered_on' => date('Y-m-d H:i:s', WPSCommon::localTs()),
'status' => $status,
'ouid' => $ouid,
'payment_method' => 'Paypal',
'payment_status' => 'Complete',
'share_cart_discount_amount' => $share_cart_discount,
'price_inc_tax' => $tax_included_in_price,
);
$data = array_map(function($value) {
if (is_string($value) === true) {
$value = iconv(mb_detect_encoding($value, mb_detect_order(), true), 'UTF-8', $value);
}
return $value;
}, $data);
if ($cart_object == '') {
$data['delivery_status'] = 'Pending'; //Cart object *should* never be blank, but if it is then set delivery status to "Pending"
} else if ($cart_object->isAllDigital()) {
$data['delivery_status'] = 'Complete';
} else if ($cart_object->isAllPhysical()) {
$data['delivery_status'] = 'Pending';
} else {
$data['delivery_status'] = 'Pending';
}
// Verify the first items in the IPN are for products managed by WPS. It could be an IPN from some other type of transaction.
$productsTable = WPSCommon::getTableName('products');
$orderItemsTable = WPSCommon::getTableName('order_items');
//$sql = "SELECT id from $productsTable where item_number = '" . $pp['item_number1'] . "'";
//$productId = $wpdb->get_var($sql);
//Let's check if the product ID is one of our photoseller gallery items
if (strpos($pp['item_number1'], 'FG_') === FALSE) {
$photoseller_item = get_post_meta($pp['item_number1'], '_wpps_gallery_id', true);
if (empty($photoseller_item)) {
WPSCommon::log("This is not an IPN that should be managed by WPS!");
throw new Exception("This is not an IPN that should be managed by WPS");
}
}
// Look for the 100% coupons shipping item and move it back to a shipping costs rather than a product
if ($data['shipping'] == 0) {
for ($i = 1; $i <= $numCartItems; $i++) {
$itemNumber = strtoupper($pp['item_number' . $i]);
if ($itemNumber == 'SHIPPING') {
$data['shipping'] = isset($pp['mc_gross_' . $i]) ? $pp['mc_gross_' . $i] : $pp['mc_gross' . $i];
}
}
}
$res = $wpdb->insert($orderTable, $data);
if ($res === false) {
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Failed to insert the following into the order table: " . print_r($data, true));
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] wpdb last error: " . $wpdb->last_error);
return false;
}
$orderId = $wpdb->insert_id;
//$product = new WPSProduct();
for ($i = 1; $i <= $numCartItems; $i++) {
//$sql = "SELECT id from $productsTable where item_number = '" . $pp['item_number' . $i] . "'";
//$productId = $wpdb->get_var($sql);
$productId = $pp['item_number' . $i];
if (strpos($productId, 'FG_') !== FALSE || $productId > 0) {
//$product->load($productId);
//$product_name = $product->name;
$product_name = html_entity_decode($pp['item_name' . $i], ENT_NOQUOTES, 'UTF-8');
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Product Name: ".$product_name);
/*
// Decrement inventory
$info = $pp['item_name' . $i];
if(strpos($info, '(') > 0) {
$start = strpos($info, '(');
$end = strpos($info, ')');
$length = $end - $start;
$variation = substr($info, $start+1, $length-1);
WPSCommon::log("PayPal Variation Information: $variation\n$info");
}
$qty = $pp['quantity' . $i];
WPSProduct::decrementInventory($productId, $variation, $qty);
*/
if ($hasDigital == false) {
//$hasDigital = $product->isDigital();
if (strpos($product_name, 'Digital :') > -1) {
$hasDigital = true;
} else {
$hasDigital = false;
}
}
// PayPal is not consistent in the way it passes back the item amounts
$amt = 0;
if (isset($pp['mc_gross' . $i])) {
$amt = $pp['mc_gross' . $i];
} elseif (isset($pp['mc_gross_' . $i])) {
$amt = $pp['mc_gross_' . $i] / $pp['quantity' . $i];
}
// Look for Gravity Form Entry ID
$formEntryId = 'none'; //setting this to a string - some servers don't like an empty value
if (is_array($gfIds) && !empty($gfIds) && isset($gfIds[$i])) {
$formEntryId = $gfIds[$i];
}
$duid = md5($pp['txn_id'] . '-' . $orderId . '-' . $productId);
//Get some details from the cart object
$cart_item_index = $i - 1;
$cart_item = $cart_object->getItem($cart_item_index);
$gallery_id = $cart_item->wps_photo_product->gallery_id;
$variation_id = $cart_item->getVariationID();
$is_full_gallery_purchase = 0;
$digital_ratio = is_numeric($cart_item->getDigitalRatio()) ? $cart_item->getDigitalRatio() : '0.00';
if ($cart_item->isFullGalleryPurchase() === TRUE) {
$is_full_gallery_purchase = 1;
}
$data = array(
'order_id' => $orderId,
'product_id' => $productId,
'item_number' => $pp['item_number' . $i],
'product_name' => $product_name,
'product_price' => $amt,
'description' => $product_name,
'quantity' => $pp['quantity' . $i],
'gallery_id' => $gallery_id,
'digital_ratio' => $digital_ratio,
'variation_description' => $product_name,
'duid' => $duid,
'form_entry_ids' => $formEntryId,
'date' => date('Y-m-d H:i:s'),
'full_gallery_purchase' => $is_full_gallery_purchase,
'variation_id' => $variation_id
);
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Just about to insert the following ordered item into the order_items table: " . print_r($data, true));
$res = $wpdb->insert($orderItemsTable, $data);
if ($res === false) {
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Error inserting row into WPPS_TBL_CART_ORDER_ITEMS. Tried to insert the following data: " . print_r($data, true));
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] wpdb last error: " . $wpdb->last_error);
}
//Let's update inventory amount if applicable
$custom_variation_meta_id = $cart_item->getCustomVariationID();
if (!empty($custom_variation_meta_id)) {
$inv_update = WPSOrder::updateInventory($custom_variation_meta_id, $pp['quantity' . $i]);
}
} else {
WPSCommon::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Invalid Product ID: " . $productId);
}
}//end for loop
if ($coupon_code != 'none') {
WPSCommon::log('$coupon_code = ' . $coupon_code);
WPSCommon::log("will reedem coupon now");
$promo = new WPSPromotion();
$promo->loadByCode($coupon_code);
if ($promo) {
WPSPromotion::redeemCoupon($promo->code);
}
}
WPSCommon::log("Calling WPSCommon::sendEmailOnPurchase");
WPSCommon::sendEmailOnPurchase($orderId);
do_action('wps_ppp_after_email_sent', $orderId);
// Process affiliate reward if necessary
if (!empty($referrer)) {
WPSCommon::awardCommission($orderId, $referrer);
}
return $orderId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment