Shippo change shipping rate - shippo

I'm using the Shippo API to try and set my rate/parcel to USPS priority. Per the docs I feel like I need to add/edit the $rate array, but I can't seem to figure it out.
// Select the rate you want to purchase.
// We simply select the first rate in this example.
// $rate = $shipment["rates_list"][0];
$rate = array(
'object_state' => 'VALID',
'provider' => 'USPS',
'servicelevel_name' => 'Priority Mail',
'servicelevel_token' => 'usps_priority'
);
// Purchase the desired rate
$transaction = Shippo_Transaction::create(array(
'rate'=> $rate["object_id"],
//'rate' => $rate["usps_priority"],
'async'=> false
));

Looks like our InstaLabel feature is perfect for you https://goshippo.com/shipping-api/instalabel
There is a complete PHP example on that link but here's the bit of code you specified:
$transaction = Shippo_Transaction::create( array(
'shipment' => $shipment,
'carrier_account' => 'b741b99f95e841639b54272834bc478c',
'servicelevel_token' => 'usps_priority',
);
);

Related

Magento 2 - Programatically Add Credit Card into Vault (BrainTree)

I need to Add Credit Card details in to Vault Programmatically (BrainTree) in Magento 2.1.5
Basically what i want is After LoginIn there will be a separate section for Saved Cards . In that Customer is used to Add/edit/delete All his Credit card details.
the Below Code is used to list all the Credit Card saved by the Customer
use Magento\Vault\Api\PaymentTokenManagementInterface;
use Magento\Customer\Model\Session;
...
// Get the customer id (currently logged in user)
$customerId = $this->session->getCustomer()->getId();
// Card list
$cardList = $this->paymentTokenManagement->getListByCustomerId($customerId);
Now what i want is how to Add the Card Details to the Vault ?
Below is the Code to Add card in core php
$result = Braintree_Customer::create(array(
'firstName' => 'first name',
'lastName' => 'last name',
'company' => 'company',
'email' => 'xxxx#gmail.com',
'phone' => '1234567890',
'creditCard' => array(
'cardholderName' => 'xxx xxx',
'number' => '4000 0000 0000 0002 ',
'expirationMonth' => '10',
'expirationYear' => 2020,
'cvv' => '123',
'billingAddress' => array(
'firstName' => 'My First name',
'lastName' => 'My Last name'
)
)
));
But how can i do this same process in magento 2.
Thanks for the help
First, you have to create a payment token from the card data:
use Magento\Vault\Model\CreditCardTokenFactory;
...
$paymentToken = $this->creditCardTokenFactory->create();
$paymentToken->setExpiresAt('Y-m-d 00:00:00');
$paymentToken->setGatewayToken('card_112371K7-28BB-4O3X-CCG9-1034JHK27D88');
$paymentToken->setTokenDetails([
'type' => 'Visa',
'maskedCC' => '1111',
'expirationDate' => '06/2019'
]);
$paymentToken->setIsActive(true);
$paymentToken->setIsVisible(true);
$paymentToken->setPaymentMethodCode('your_payment_method_code');
$paymentToken->setCustomerId($customerId);
$paymentToken->setPublicHash($this->generatePublicHash($paymentToken));
Then you can save the payment token:
use Magento\Vault\Api\PaymentTokenRepositoryInterface;
...
$this->paymentTokenRepository->save($paymentToken);
This is just an example you can start with. In a real world situation, you would also want to check that the token doesn't already exist, an also try a payment authorisation on the card to make sure it's actually usable and valid.
In order to check if a payment token exists or not, you can use this:
use Magento\Vault\Api\PaymentTokenManagementInterface;
...
$this->paymentTokenManagement->getByPublicHash( $paymentToken->getPublicHash(), $paymentToken->getCustomerId() );
You can have a look at the core Magento 2 classes mentioned here to know more about the functions available for payment token handling.
Good luck!
Replace objectManager when use in projects
<?php
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Vault\Model\AccountPaymentTokenFactory;
use Magento\Vault\Model\PaymentToken;
use Magento\Vault\Model\PaymentTokenRepository;
/** #var EncryptorInterface $encryptor */
$encryptor = $objectManager->get(EncryptorInterface::class);
/** #var PaymentToken $paymentToken */
$paymentToken = $objectManager->create(PaymentToken::class);
$paymentToken
->setCustomerId($customer->getId())
->setPaymentMethodCode('payflowpro')
->setType(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT)
->setGatewayToken('mx29vk')
->setPublicHash($encryptor->hash($customer->getId()))
->setTokenDetails(json_encode(['payerEmail' => 'john.doe#example.com']))
->setIsActive(true)
->setIsVisible(true)
->setExpiresAt(date('Y-m-d H:i:s', strtotime('+1 year')));
/** #var PaymentTokenRepository $tokenRepository */
$tokenRepository = $objectManager->create(PaymentTokenRepository::class);
$tokenRepository->save($paymentToken);

PayPal express checkout instant update callback not being called [Sandbox]

I'm having troubles with the PayPal callback feature, i can't for the life of me get it to work at all. I have double checked the callback URL path, it's correct. When the user logs into paypal, it always just returns the default shipping rate. I'm just really not sure what i am missing here, if anyone can help out. Also, i have the callback timeout set to 6, though it seems it only takes about 3 - 4 seconds for it to fail and return the default shipping rate.
I've followed the documentation here https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECInstantUpdateAPI/ and applied it to my website. I've also made sure i am logged into sandbox too.
SetExpressCheckout params:
// SetExpressCheckout
$params = array (
'METHOD' => 'SetExpressCheckout',
'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
'VERSION' => $version, // 124.0
'USER' => $paypal_user,
'PWD' => $paypal_password,
'SIGNATURE' => $signature,
'L_SHIPPINGOPTIONNAME0' => 'Flat',
'L_SHIPPINGOPTIONLABEL0' => 'N/A',
'L_SHIPPINGOPTIONAMOUNT0' => '6.99',
'L_SHIPPINGOPTIONISDEFAULT0' => 'true',
'PAYMENTREQUEST_0_INSURANCEOPTIONSOFFERED' => 'false',
'PAYMENTREQUEST_0_SHIPPINGAMT' => $shipping_default, // 6.99
'PAYMENTREQUEST_0_ITEMAMT' => $cart_total,
'PAYMENTREQUEST_0_AMT' => $cart_total + $shipping_default,
'MAXAMT' => $cart_total + 30, // 30 is the total possible shipping amount
'PAYMENTREQUEST_0_CURRENCYCODE' => $paypal_currency, // AUD
'RETURNURL' => $paypal_return,
'CANCELURL' => $paypal_cancel,
'CALLBACK' => 'HTTP://localhost/moes/php/paypal_callback_php.php',
'CALLBACKTIMEOUT' => 6,
'CALLBACKVERSION' => '61.0',
'ALLOWNOTE' => 1,
'PAYMENTREQUEST_0_INVNUM' => '123' /*$invoice_number*/,
'PAYMENTREQUEST_0_TAXAMT' => $tax, // 0.00
);
// List each product and add to exress check-out array
foreach ($paypal_products as $k => $product){
$params["L_PAYMENTREQUEST_0_NAME$k"] = $product['name'];
$params["L_PAYMENTREQUEST_0_AMT$k"] = number_format($product['price'],2);
$params["L_PAYMENTREQUEST_0_QTY$k"] = $product['qty'];
$params["L_PAYMENTREQUEST_0_NUMBER$k"] = $product['code'];
$params["L_PAYMENTREQUEST_0_DESC$k"] = '1';
/* Optional shipping options to calculate shipping costs on callback
Option weight (L_PAYMENTREQUEST_n_ITEMWEIGHTVALUEm, L_PAYMENTREQUEST_n_ITEMWEITHTUNITm)
Option height (L_PAYMENTREQUEST_n_ITEMHEIGHTVALUEm, L_PAYMENTREQUEST_n_ITEMHEIGHTUNITm)
Option length (L_PAYMENTREQUEST_n_ITEMLENGTHVALUEm, L_PAYMENTREQUEST_n_ITEMLENGTHUNITm)
Option width (L_PAYMENTREQUEST_n_ITEMWIDTHVALUEm, L_PAYMENTREQUEST_n_ITEMWIDTHUNITm)*/
}
Callback script:
<?php
// Populate variables into local variables
$method = $_POST['METHOD'];
$version = $_POST['CALLBACKVERSION'];
$token = $_POST['TOKEN'];
$currencycode = $_POST['CURRENCYCODE'];
$localecode = $_POST['LOCALECODE'];
$street = $_POST['SHIPTOSTREET'];
$street2 = $_POST['SHIPTOSTREET2'];
$city = $_POST['SHIPTOCITY'];
$state = $_POST['SHIPTOSTATE'];
$country = $_POST['SHIPTOCOUNTRY'];
$zip = $_POST['SHIPTOZIP'];
// Setting shipping rate based on country [Test only]
if ($country == "US"){
echo "METHOD=CallbackResponse&OFFERINSURANCEOPTION=false&L_SHIPPINGOPTIONNAME0=FLat&L_SHIPPINGOPTIONLABEL0=N/A&L_SHIPPINGOPTIONAMOUNT0=10.00&L_TAXAMT0=1.00&L_INSURANCEAMOUNT0=9.00&L_SHIPPINGOPTIONISDEFAULT0=true";
} else {
echo "METHOD=CallbackResponse&OFFERINSURANCEOPTION=false&L_SHIPPINGOPTIONNAME0=FLat&L_SHIPPINGOPTIONLABEL0=N/A&L_SHIPPINGOPTIONAMOUNT0=30.00&L_TAXAMT0=1.00&L_INSURANCEAMOUNT0=9.00&L_SHIPPINGOPTIONISDEFAULT0=true";
}
?>
I'm guessing i missing something fundamental here, or i'm going about it completely the wrong way.
The solution to my problem was :
localhost/moes/php/paypal_callback_php.php
Obviously PayPal can't send a HTTP request to 'localhost'. My WAMP server is not configured to be accessible over the internet.

How to set up Omnipay with Laravel?

I am using this packet:
https://github.com/barryvdh/laravel-omnipay
In my controller I added:
$params = [
'amount' => '10',
'issuer' => 22,
'description' => 'desc',
'returnUrl' => URL::action('PurchaseController#returnApi', [43]),
];
$response = Omnipay::purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
return $response->getRedirectResponse();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
Here is my omnipay.php conf file:
<?php
return array(
/** The default gateway name */
'gateway' => 'PayPal_Express',
/** The default settings, applied to all gateways */
'defaults' => array(
'testMode' => true,
),
/** Gateway specific parameters */
'gateways' => array(
'PayPal_Express' => array(
'username' => '',
'landingPage' => array('billing', 'login'),
),
),
);
But get this error:
call_user_func_array() expects parameter 1 to be a valid callback,
class 'Omnipay\Common\GatewayFactory' does not have a method
'purchase'
Anyone can help me set this?
I created app on paypal and have details about it but don't know how to set it with this API...
I recommend that you switch from PayPal Express to PayPal REST. It is newer and has better documentation.
I have looked through the laravel-omnipay package and I can't see a use case for it. I would just code to the omnipay package directly.
I recommend that you create a unique transaction ID for each transaction and provide that as part of the URLs for returnUrl and cancelUrl so that you can identify which transaction you are dealing with in the return and cancel handlers.
I think that you are taking the examples in the laravel-omnipay package too literally. You don't need or want those echo statements there. You should be capturing the response from purchase() even if it is a redirectResponse and doing a getTransactionReference() check on it, because you will need that transaction reference later, e.g. for transaction lookup. You should store it in the transaction record that you created before calling purchase().
You may use
use Omnipay\Omnipay;
in your controller, change it to
use Omnipay;

Can someone provide a php sample using nusoap/sugarcrm api to create an acct/lead in sugarcrn?

Can someone provide a sample code chunk of php using the sugarcrm API/nusoap for adding creating an acct. and then linking a lead to the acct?
I've got a sample function that adds a lead, and I can see how to create an acct, but I can't see how to tie a lead to the acct, to simulate the subpanel process in the sugarcrm acct/subpanel process.
thanks
// Create a new Lead, return the SOAP result
function createLead($data)
{
// Parse the data and store it into a name/value list
// which will then pe passed on to Sugar via SOAP
$name_value_list = array();
foreach($data as $key => $value)
array_push($name_value_list, array('name' => $key, 'value' => $value));
// Fire the set_entry call to the Leads module
$result = $this->soap->call('set_entry', array(
'session' => $this->session,
'module_name' => 'Leads',
'name_value_list' => $name_value_list
));
return $result;
}
$result = $sugar->createLead(array(
'lead_source' => 'Web Site',
'lead_source_description' => 'Inquiry form on the website',
'lead_status' => 'New',
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email1' => $_POST['email'],
'description' => $_POST['message']
));
You need to find the ID for the account and assign that ID to whatever the account_id field name is in the Lead Module. I have run into a couple things like this before and I have found it easier to go straight to the Sugar database. So, write a statement that will return the account is, for example: SELECT id WHERE something_in_the_account_table = something else;
Then you can assign that id in your $result array. I hope it helps. I didn't have any code or documentation in front of me or I would have helped more.

not getting email for custom field woocommerce

I am using woocommerce (free plugin).. I am trying to add one custom field to the billing fields..
here it is:
// ADDED HOW YOU GOT TO KNOW ABOUT OUR SERVICE FIELD
add_filter( 'woocommerce_checkout_fields' , 'About_Our_Service' );
// Our hooked in function - $fields is passed via the filter!
function About_Our_Service( $fields ) {
$fields['billing']['billing_meat'] = array(
'label' => __('How you Got to Know About Our Service?', 'woocommerce'),
'placeholder' => _x('', 'placeholder', 'woocommerce'),
'required' => false,
'clear' => false,
'type' => 'select',
'options' => array(
'google-ads' => __('Google', 'woocommerce' ),
'google-search' => __('Yahoo', 'woocommerce' ),
'warrior-forum' => __('Bing', 'woocommerce' ),
'facebook' => __('Facebook', 'woocommerce' ),
'other' => __('Other', 'woocommerce' ),
)
);
return $fields;
}
The problem is: I am not getting the value in my mail for the custom field which was added to the billing fields.. Anyone who already used woocommerce can help me on this... ?
I already created some more custom fields which was added to the checkout (BUT these're not added along with the core fields), for these fields i'm able to get values in my mail..
By the ay, i checked this thread: but didn't much info related to mail..
please kindly someone look into this..
For future readers, custom billing/shipping fields are saved as post meta for the order post. So in general, you can retrieve them with the typical WordPress get_post_meta() function.
But in WooCommerce 2.2, you don't need to as you can pass the field name directly to an array of fields that WC will show as a list in the email:
// pre-WooCommerce 2.3
function kia_email_order_meta_keys( $keys ) {
$keys['Some field'] = '_some_field';
return $keys;
}
add_filter('woocommerce_email_order_meta_keys', 'kia_email_order_meta_keys');
This method has been deprecated in version 2.3, probably so translation can be better. As of 2.3 you will need to target a different filter and send slightly different data.
// WooCommerce 2.3+
function kia_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
$fields['some_field'] = array(
'label' => __( 'Some field', 'my-plugin-textdomain' ),
'value' => get_post_meta( $order->id, '_some_field', true );
);
return $fields;
}
add_filter('woocommerce_email_order_meta_fields', 'kia_email_order_meta_keys', 10, 3 );
I wrote a tutorial on Customizing WooCommerce Checkout Fields
I believe this answer, in the codex is specifically meant for this purpose:
http://wcdocs.woothemes.com/snippets/add-a-custom-field-in-an-order-to-the-emails
I haven't implemented this myself but it's probably your best shot.