So, I've developed the following code:
const MAILGUN_API_MAX_LIMIT = 300; //max in documentation
$mgClient = new Mailgun\Mailgun("<mailgun_key>");
$domain = "<my_domain>";
$resultItems = array();
try {
$result = null;
$endTime_Epoch = time();
$startTime_Epoch = $endTime_Epoch - 1440000; //400 hours
$queryParams = array(
'begin' => $endTime_Epoch,
'end' => $startTime_Epoch,
'limit' => MAILGUN_API_MAX_LIMIT,
'ascending' => 'no',
'event' => 'rejected OR failed',
);
$request_url = "$domain/events";
do {
$result = $mgClient->get($request_url, $queryParams);
if(!$result->http_response_body) {
/*...*/
} else if($result->http_response_code != 200) {
/*...*/
} else {
$resultItems[] = $result->http_response_body->items;
if(count($result->http_response_body->items) == MAILGUN_API_MAX_LIMIT) {
$request_url = $result->http_repsonse_body->paging->next;
}
}
} while($result && $result->http_response_body && count($result->http_response_body->items) == MAILGUN_API_MAX_LIMIT);
} catch (Exception $e) {
echo $e->getMessage()
}
But I'm having trouble getting it to page through the next set of requests if the limit ever gets hit (it probably won't, but it'd be bad in the event that something happened that made it happen).
I've tried reading mailgun's api doc, but i cannot, for the life of me, figure out what it is talking about with this:
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';
$nextPage = 'W3siYSI6IGZhbHNlLC';
# Make the call to the client.
$result = $mgClient->get("$domain/events/$nextPage");
But i can't figure out what that $nextPage is supposed to be. I've tried peeling off the start of the paging->next so it just ends up being $domain/events/, but that doesn't seem to be paging though it. I'm not really sure what to do here, or even what I'm supposed to do.
I know this is a bit later than you would've hoped, but I've also been doing some stuff with the Mailgun and PHP lately.
So $nextPage is a value provided after your first API requests, so you don't need it at the start. Simply make your normal request like so
$result = $mailgun->get("$domain/events", $queryString);
// then we can get our 'Next Page' uri provided by the request
$nextURI = $result->http_response_body->paging->next;
// now we can use this to grab our next page of results
$secondPageResults = $mailgun->get($nextURI, $queryString);
Once thing worth noting though, is that Mailgun seems to always provide a 'next' link even when you've got all the results you want.
In my project I collected all results using a while loop after getting my initial records:
$hasNext = count($items) >= $queryLimit;
while($hasNext) {
$nextResult = $mailgun->get($lastResult->http_response_body->paging->next, $queryString);
$nextItems = $nextResult->http_response_body->items;
$items = array_merge($items, $nextItems);
$hasNext = count($nextItems) >= $queryLimit;
$lastResult = $nextResult;
}
Hope this helps!
I need to let customer edit their pending payment order. By default, woocommerce only allow change the payment method. So, I have created a custom template for this feature.
The problem now I encountered is I can't get the shipping packages in the template.
Here is the code that I adapted from the wc_cart_totals_shipping_html() :
$packages = WC()->shipping->get_packages();
print_r($packages);
foreach ( $packages as $i => $package ) {
//blah blah blah
}
The print_r($packages) give me the null array. But on the checkout page, it's working fine.
Any idea why? Or, get the shipping packages by other method?
Please try this -
global $woocommerce;
$customerZipCode = 75098;
$zipResultArr = csd_check_zip_and_state($customerZipCode);
$bh_packages = $woocommerce->cart->get_shipping_packages();
$bh_packages[0]['destination']['state'] = $zipResultArr['state'];
$bh_packages[0]['destination']['postcode'] = $customerZipCode ;
$bh_packages[0]['destination']['city'] = $zipResultArr['city'];
$bh_packages[0]['destination']['address'] = '';
$bh_packages[0]['destination']['address_2'] = '';
//Calculate costs for passed packages
$bh_shipping_methods = array();
foreach( $bh_packages as $bh_package_key => $bh_package ) {
$bh_shipping_methods[$bh_package_key] = $woocommerce->shipping->calculate_shipping_for_package($bh_package, $bh_package_key);
}
$shippingArr = $bh_shipping_methods[0]['rates'];
if(!empty($shippingArr)) {
$response = array();
foreach ($shippingArr as $value) {
$shipping['label'] = $value->label;
$shipping['cost'] = $value->cost;
$response['shipping'][] = $shipping;
}
}
// This is your shipping
print_r($response);
The following serialized string is being pulled from the meta data of a Woocommerce product.
a:2:{s:17:"set_51fb76f97cc57";a:6:{s:15:"conditions_type";s:3:"all";s:10:"conditions";a:1:{i:1;a:2:{s:4:"type";s:8:"apply_to";s:4:"args";a:2:{s:10:"applies_to";s:5:"roles";s:5:"roles";a:1:{i:0;s:14:"trade_customer";}}}}s:9:"collector";a:1:{s:4:"type";s:7:"product";}s:4:"mode";s:5:"block";s:5:"rules";a:1:{i:1;a:4:{s:4:"from";s:0:"";s:2:"to";s:0:"";s:4:"type";s:14:"price_discount";s:6:"amount";s:0:"";}}s:10:"blockrules";a:1:{i:1;a:5:{s:4:"from";s:1:"*";s:6:"adjust";s:1:"1";s:4:"type";s:16:"fixed_adjustment";s:6:"amount";s:4:"8.37";s:9:"repeating";s:3:"yes";}}}s:17:"set_51fb76f97d6a2";a:6:{s:15:"conditions_type";s:3:"all";s:10:"conditions";a:1:{i:1;a:2:{s:4:"type";s:8:"apply_to";s:4:"args";a:2:{s:10:"applies_to";s:5:"roles";s:5:"roles";a:1:{i:0;s:19:"bulk_trade_customer";}}}}s:9:"collector";a:1:{s:4:"type";s:7:"product";}s:4:"mode";s:5:"block";s:5:"rules";a:1:{i:1;a:4:{s:4:"from";s:0:"";s:2:"to";s:0:"";s:4:"type";s:14:"price_discount";s:6:"amount";s:0:"";}}s:10:"blockrules";a:1:{i:1;a:5:{s:4:"from";s:1:"*";s:6:"adjust";s:1:"1";s:4:"type";s:16:"fixed_adjustment";s:6:"amount";s:5:"9.428";s:9:"repeating";s:3:"yes";}}}}
That's using Woocommerce with the Dynamic Pricing plugin.
I also have this function which I am writing in order to pull out the variable product data and display it on the site:
function mi_price_adjust(){
global $post, $current_user, $user_roles;
$meta = get_post_meta($post->ID);
$curPrice = (float)$meta['_regular_price'][0];
$variations = unserialize($meta['_pricing_rules'][0]);
$user_roles = $current_user->roles;
$theRoll = '';
$thePrice = $curPrice;
foreach($user_roles as $miroll){
if(in_array($miroll, $user_roles)){
$theRoll = $miroll;
}
}
if($theRoll != ''){
foreach($variations as $curvar){
$var_roll = $curvar['conditions'][1]['args']['roles'][0];
$var_cost = (float)$curvar['blockrules'][1]['amount'];
if($var_roll == $theRoll){
$thePrice = $curPrice - $var_cost;
}
}
}
if($thePrice != $curPrice){
return "<strike>".$curPrice."</strike><br /><span class=\"youpayText\">You pay £$thePrice</span>";
}else{
return $thePrice;
}
}
Everything is working fine apart from one thing. I am getting the following error:
Invalid argument supplied for foreach
The line in question is
foreach($variations as $curvar){
And the $variations variable is being populated using this:
$variations = unserialize($meta['_pricing_rules'][0]);
Which returns the serialized string at the top of this post.
Can anyone shed any light on why this might be happening and what we might be able to do to either fix it or circumvent it?
Im using this code from google api
I am getting all of the goals names and number
But I cant see a way to get the goal completed amount
This is what I get:
Account ID = xxx
Web Property ID = xxx
Internal Web Property ID = xxx
Profile ID = xxx
Goal Number = 1
Goal Name = Open User (MT Register)
Goal Value = 0
Goal Active = 1
Goal Type = URL_DESTINATION
Created = 2012-07-22T10:20:02.183Z
Updated = 2012-08-15T12:43:06.045Z
Goal URL = /04_thankyou.php
Case Sensitive =
Match Type = REGEX
First Step Required = 1
Destination Goal Steps
Step Number = 1
Step Name = abc
Step URL = /01_insert_phone.php
Step Number = 2
Step Name = abcd
Step URL = /02_progress.step
Step Number = 3
Step Name = abcde
Step URL = /03_insert_pincode.php
This is the code:
function getEventDetailsHtml(&$details) {
$html = '<h4>Event Goal</h4><pre>' .
'Use Event Value = ' . $details->getUseEventValue();
// Get all the event goal conditions.
$conditions = $details->getEventConditions();
foreach ($conditions as &$condition) {
$html .= "Event Type = $condition->getEventType()";
$eventType = $condition->getType();
if ($condition->getType() == 'VALUE') {
// Process VALUE.
$html .= "Comparison Type = $condition->getComparisonType()" .
"Comparison Value = $condition->getComparisonValue()";
} else {
// Process CATEGORY, ACTION, LABEL.
$html .= "Match Type = $condition->getMatchType()" .
"Expression = $condition->getExpression()";
}
}
return $html . '</pre>';
}
function getVisitNumPagesDetailsHtml(&$details) {
$html = '<h4>Visit Num Pages Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getVisitTimeOnSiteDetailsHtml(&$details) {
$html = '<h4>Visit Time On Site Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getUrlDestinationDetailsHtml(&$details) {
$html .= <<<HTML
<pre>
Goal URL = {$details->getUrl()}
Case Sensitive = {$details->getCaseSensitive()}
Match Type = {$details->getMatchType()}
First Step Required = {$details->getFirstStepRequired()}
</pre>
HTML;
$html .= '<h4>Destination Goal Steps</h4>';
$steps = $details->getSteps();
if (count($steps) == 0) {
$html .= '<p>No Steps Configured</p>';
} else {
foreach ($steps as &$step) {
$html .= <<<HTML
<pre>
Step Number = {$step->getNumber()}
Step Name = {$step->getName()}
Step URL = {$step->getUrl()}
</pre>
HTML;
}
}
return $html;
}
require_once 'google_api.php';
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
try {
$goals = $analytics->management_goals
->listManagementGoals('25788360',
'UA-25788360-20',
'~all');
} catch (Exception $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
$html = '';
$items = $goals->getItems();
foreach ($items as &$goal) {
$html .= "
<pre>
Account ID = {$goal->getAccountId()}
Web Property ID = {$goal->getWebPropertyId()}
Internal Web Property ID = {$goal->getInternalWebPropertyId()}
Profile ID = {$goal->getProfileId()}
Goal Number = {$goal->getId()}
Goal Name = {$goal->getName()}
Goal Value = {$goal->getValue()}
Goal Active = {$goal->getActive()}
Goal Type = {$goal->getType()}
Created = {$goal->getCreated()}
Updated = {$goal->getUpdated()}
</pre>";
// Now get the HTML for the type of goal.
switch($goal->getType()) {
case 'URL_DESTINATION':
$html .= getUrlDestinationDetailsHtml(
$goal->getUrlDestinationDetails());
break;
case 'VISIT_TIME_ON_SITE':
$html .= getVisitTimeOnSiteDetailsHtml(
$goal->getVisitTimeOnSiteDetails());
break;
case 'VISIT_NUM_PAGES':
$html .= getVisitNumPagesDetailsHtml(
$goal->getVisitNumPagesDetails());
break;
case 'EVENT':
$html .= getEventDetailsHtml(
$goal->getEventDetails());
break;
}
echo $html;
}
It seems like you are using the Management API. This is meant for management purposes only. Getting and setting goals.
If you want data from goals as well you want to be looking at the Core Reporting API.
The available data for goals can be found here:
https://developers.google.com/analytics/devguides/reporting/core/dimsmets/goalconversions
The implementation guide can be found here:
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
I did not provide a full implementation example seeing that you already know how to setup the use of a Google API.
Good luck with you quest!
EDIT:
Added an example on how to use it:
<?php
$client = new apiAnalyticsService();
function queryCoreReportingApi() {
$optParams = array( //OPTINAL SETTINGS
'dimensions' => '', //A comma-separated list of Multi-Channel Funnels dimensions. E.g., 'mcf:source,mcf:medium'. (string)
'sort' => '', //A comma-separated list of dimensions or metrics that determine the sort order for the Analytics data. (string)
'filters' => '', //A comma-separated list of dimension or metric filters to be applied to the Analytics data. (string)
'start-index' => '', //An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. (integer, 1+)
'fields' => '', //Selector specifying which fields to include in a partial response.
'max-results' => '25'); //The maximum number of entries to include in this feed. (integer)
return $service->data_mcf->get(
$id, //Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID. (string)
'2010-01-01', //Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD. (string)
'2010-01-15', //End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD. (string)
'ga:totalConversions', //A comma-separated list of Multi-Channel Funnels metrics. E.g., 'mcf:totalConversions,mcf:totalConversionValue'. At least one metric must be specified. (string)
$optParams);
}
I am trying to add new values to an attribute option in Magento using a script to speed up the process since I have over 2,000 manufacturers.
Here is a piece of code that I used to perform exactly this task. Create a custom module (using ModuleCreator as a tool) and then create a mysql4-install-0.1.0.php under the sql/modulename_setup folder. It should contain the following (adapted to your own data, of course!).
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$aManufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$iProductEntityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$aOption = array();
$aOption['attribute_id'] = $installer->getAttributeId($iProductEntityTypeId, 'manufacturer');
for($iCount=0;$iCount<sizeof($aManufacturers);$iCount++){
$aOption['value']['option'.$iCount][0] = $aManufacturers[$iCount];
}
$installer->addAttributeOption($aOption);
$installer->endSetup();
More documentation on the Magento wiki if you want.
If you don't want to do it in a custom module, you could just create a php file that starts with:
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
Answer of Jonathan is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key=>$manufacturer) {
$option['value'][$key.'_'.$manufacturer][0] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
More information can be found here.
I have created a function to dynamically add option to attribute
public function addAttributeOptions($attributeCode, $argValue)
{
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
$id = $attribute->getSource()->getOptionId($argValue);
if ($id)
return $id;
}
$value = array('value' => array(
'option' => array(
ucfirst($argValue),
ucfirst($argValue)
)
)
);
$attribute->setData('option', $value);
$attribute->save();
//return newly created option id
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
return $attribute->getSource()->getOptionId($argValue);
}
}
You can add an option to your attribute by providing code and option value
$this->addAttributeOptions('unfiorm_type', 'leotartd')
Important! (Hopefully this helps somebody, cause I was stuck like 2h with this issue)
If you are using special characters (such as ä, ö, ü, ß, ×, ...) make sure to encode them properly!
array_walk($manufacturers , create_function('&$val', '$val = utf8_encode($val);'));
Here a simple and very fast way....
Delete an option
/* My option value */
$value = 'A value';
/* Delete an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID from value...
if ($option_id) {
$options['delete'][$option_id] = true;
$attribute->setOption($options)->save();
}
}
/* END ! */
Add or update an option
/* Add/Update an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID...
$options['order'][$option_id] = 10; // Can be removed... Set option order...
$options['value'][$option_id] = array(
0 => $value, // Admin Store - Required !
1 => $value, // Store id 1 - If U want ! Can be removed
);
$attribute->setDefault(array($option_id)); /* If you want set option as default value */
$attribute->setOption($options)->save(); /* That's all */
}
/* END ! */
In my tutorial I am explaining how to read the options from the CSV and create the options pro grammatically.
http://www.pearlbells.co.uk/add-attribute-options-magento-scripts/
please click the tutorial for further explanation
function createAttribute($options) {
$option = array('attribute_id' =>
Mage::getModel('eav/entity_attribute')->getIdByCode(
Mage_Catalog_Model_Product::ENTITY,
'color'
)
);
for ($i = 0; $i < count($options); $i++) {
$option['value']['option'.$i][0] = $options[ $i ]; // Store View
$option['value']['option'.$i][1] = $options[ $i ]; // Default store view
$option['order']['option'.$i] = $i; // Sort Order
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
}
Answer of Arvind Bhardwaj enter code here is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
Agree with Arvind but it's only works for insert the single option value and if you want to perform insert multiple option value then you just needs to replace the code from "$option['value'][$key.''.$manufacturer] = $manufacturer;" to "$option['values'][$key.''.$manufacturer] = $manufacturer;" to this.
below is the final code
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony', 'Philips', 'Samsung', 'LG', 'Panasonic', 'Fujitsu', 'Daewoo', 'Grundig', 'Hitachi', 'JVC', 'Pioneer', 'Teac', 'Bose', 'Toshiba', 'Denon', 'Onkyo', 'Sharp', 'Yamaha', 'Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key => $manufacturer) {
$option['values'][$key . '_' . $manufacturer] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
I hope its works for insertion multiple option.