applying promotion code instead of coupon in laravel/cashier - php

i am trying to use Promotion code instead of coupon code in laravel cashier/stripe official package but i couldn't find any help in there on how to apply promotion code instead of coupon on subscription as i know how to apply coupon but i want to apply promotion code, how can i do it.
below is my code for applying coupon when creating new subscription but i don't know how can i achieve it using promotion code:
$subscription = $user->newSubscription($plan->name, $selectedPlan);
// Add the trial days if any
if ($plan->trial_days) {
$subscription = $subscription->trialDays($plan->trial_days);
}
// Add the coupon id if any
if ($request->input('coupon_id')) {
$subscription = $subscription->withCoupon($request->input('coupon_id'));
}
$subscription->create($paymentMethod->id, [
'email' => $user->email
]);

You can add promotion code by using the ->withPromotionCode() e.g.
if ($request->input('promotion_code_id')) {
$subscription = $subscription->withPromotionCode($request->input('promotion_code_id'));
}
However, this function requires the promotion code ID instead of the code, and most likely you want your user to key in the code, not the ID. In such case, you can retrieve all active promotion codes and match the code.
if ($request->has('promotion_code')) {
$stripeClient = new \Stripe\StripeClient(config('cashier.secret'));
$result = $this->stripe->promotionCodes->all(
['code' => $request->get("promotion_code"), 'active' => true]
);
if($result->isEmpty()){
// handle invalid promo code here
}
$promoCodeID = $result->first()->id;
$subscription = $subscription->withPromotionCode($promoCodeID);
}

Related

Updating and Invoicing Stripe Subscription Quantity with Invoice description laravel cashier

Good Day,
I'm working on a project involving Laravel Cashier. I want to give user's the ability to update their subscription quantity and get charged immediately (which I have been able to achieve, using the code below)
$user = Auth::user()
$user->subscription('main')->incrementAndInvoice(10000);
As much as the above works as expected, the invoice returned doesn't include a description indicating the changes instead the invoice description is blank. But when I checked the Event Data on stripe the two descriptions are there [see below image]
The above images shows a user who was currently on a subscription plan with 5000 quantities but increased to 15000 quantities. Is there a way to include these descriptions in the invoice generated.
After i checked the incrementAndInvoice() method , it only accepts two parameter (1. count, 2. Plan) as seen below;
no option to include description like we have for the charge() method. Is there any workaround to this? Any ideas or pointers in the right direction would be really appreciated.
Thanks for your help in advance.
At the time being there is no implementation to include the description in incrementAndInvoice().
So we have to implement it and before we do that please checkout Update an invoice.
First change this line: $user->subscription('main')->incrementAndInvoice(10000); to $subscription = $user->subscription('main')->incrementAndInvoice(10000); (we are assigning it to $subscription variable)
then get the invoice as below:
$new_invoice = $user->invoices()->filter(function($invoice) use ($subscription) {
return $invoice->subscription === $subscription->stripe_id;
});
After updating the subscription quantity we will add the following:
$client = new \GuzzleHttp\Client();
$request = $client->post('https://api.stripe.com/v1/invoices/' . $invoice_id, [
'auth' => [$secret_key, null]
'json' => ['description' => 'your description']
]);
$response = json_decode($request->getBody());
Or the following:
$stripe = new \Stripe\StripeClient(
$secret_key
);
$stripe->invoices->update(
$invoice_id,
['description' => 'your description']
);
Please note that:
the $invoice_id is the id of the invoice.
the $secret_key is the API key.

Using Coupon Codes with Stripe

I have a site that is using Stripe to process a subscription payments. There is only one type of subscription.
I followed this tutorial on NetTuts to do the initial setup.
Had a form working fine processing subscriptions and everything worked. Client requested a coupon code. Stripe supports this so I set out trying to add a coupon code to the existing form.
I set up coupon codes in Stripe, set my testing keys and switched to test mode in stripe.
I'm performing a couple of checks in my code:
Check to see whether a coupon was entered, if not create a new customer object without a coupon option
Check to see whether the Coupon is valid, if not return an error
If there has been a coupon entered and it is valid, then pass the matching Stripe coupon object as an option when creating a new customer.
if(isset($couponCode) && strlen($couponCode) > 0) {
$using_discount = true;
try {
$coupon = Stripe_Coupon::retrieve($couponCode);
if($coupon !== NULL) {
$cCode = $coupon;
}
// if we got here, the coupon is valid
} catch (Exception $e) {
// an exception was caught, so the code is invalid
$message = $e->getMessage();
returnErrorWithMessage($message);
}
}
try
{
if($using_discount == true) {
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => "basic_plan",
"email" => $email,
"coupon" => $cCode
));
}
else {
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => "basic_plan",
"email" => $email
));
}
$couponCode is populated with the form field correctly the same way all other fields are populated, I've triple checked that it is being pulled correctly.
When I try to submit the form without a coupon code, it charges the full amount and passes through Stripe correctly.
However if I enter either a valid OR invalid coupon code, it does not pass a coupon object with the customer object when creating a new customer object and charges the full amount when passing through Stripe.
I've looked at the code for hours and can't seem to figure out why it is always failing to recognize the discount code and pass the matching coupon object to Stripe.
This is probably a little out dated and you found a solution for your code. But it would seem all you need to do is pass through your original $couponCode as the array value for Coupon. As stated by codasaurus you are just getting an array back from stripe of the coupon, which you don't need unless you did $cCode->id and pass the ID back to your array to create a customer.
I changed when you set the $using_discount to true, as this would trigger to send a coupon code if the coupon was valid or not.
Once the coupon is actually valid we then send the coupon. You only need the value of your submitted state so $coupon is the reference to the discount in there system. Or you could use the $coupon->id if you wanted to create it that way.
Here is my take on a solution based on your code, it could be better, but I hope it helps others looking for a solution like me.
if($coupon!='' && strlen($coupon) > 0) {
try {
$coupon = Stripe_Coupon::retrieve($coupon); //check coupon exists
if($coupon !== NULL) {
$using_discount = true; //set to true our coupon exists or take the coupon id if you wanted to.
}
// if we got here, the coupon is valid
} catch (Exception $e) {
// an exception was caught, so the code is invalid
$message = $e->getMessage();
returnErrorWithMessage($message);
}
}
if($using_discount==true)
{
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
"email" => $id,
"coupon"=>$coupon) //original value input example: "75OFFMEMBER" stripe should be doing the rest.
);
}
else
{
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
"email" => $id)
);
}
Looking at the documentation https://stripe.com/docs/api#create_customer, the Stripe_Customer::create() call is looking for just the coupon code. It looks like you're passing in the entire coupon object.
Unless your first try catch fails, $couponCode already has your coupon code. Also, there are several other checks you need to perform to determine if the coupon is valid. For example, if the coupon->times_redeemed < coupon->max_redemptions, or if the coupon->redeem_by has passed, etc. You might also want to check if the customer is already using the coupon by checking the customer discount object.
If any of these checks fail, just set your $using_discount = false;

Drupal/Ubercart custom price php code for roles

Im building an e-commerce site for wholesale foods and the pricing for products change depending on the user logged in. Ive looked at member pricing and basically every module i could find to do with altering the price but they are either for drupal 6 or not really what im after. Im using Drupal 7 with ubercart 3.
Ive found this module http://drupal.org/project/uc_custom_price. It adds a field within product creation that allows custom php code to be added to each individual product which is exactly what im after. however im not that good with php which is why ive been hunting modules instead of changing code.
What ive got at the moment is:
if ([roles] == 'test company') {
$item->price = $item->price*0.8;
}
Except the [roles] part is the wrong thing to use there and it just throws errors. Ive tried using things like $users->uid =='1' to try to hook onto a user like that but that didnt work either.
what would be the correct variable to put there?
thanks
try this Drupal 7 global $user object
global $user; // access the global user object
if(in_array("administrator",$user->roles)){ // if its administrator
$item->price = $item->price*0.8;
}elseif(in_array("vip",$user->roles)){ // if its a vip
//..
}elseif(in_array("UserCompanyX",$user->roles)){ // if its a user from company X
//..
}
or
if($user->roles[OFFSET] == "ROLE"){
// price calculation
}
$user->roles is an array of the roles assigned to the user.
hope it helped
Make your own module with UC Price API:
http://www.ubercart.org/docs/developer/11375/price_api
function example_uc_price_handler() {
return array(
'alter' => array(
'title' => t('Reseller price handler'),
'description' => t('Handles price markups by customer roles.'),
'callback' => 'example_price_alterer',
),
);
}
function example_price_alterer(&$price_info, $context, $options = array()){
global $user;
if (in_array("reseller", $user->roles)) { //Apply 30% reseller discount
$price_info["price"] = $context["subject"]["node"]->sell_price - (
$context["subject"]["node"]->sell_price * 0.30) ;
}
return;
}
See also: http://www.ubercart.org/forum/development/14381/price_alteration_hook

Magento Questions get customer details and onepage/checkout/success doesn't sending email

How to get customers data so i can pass it to a gateway payment.
Here is my model:
public function getStandardCheckoutFormFields() {
$orderIncrementId = $this->getCheckout()->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
//$order = $this->get_sale_order($orderIncrementId);
echo Mage::getModel('customer/customer')->load($orderIncrementId);
$productArray = array();
foreach ($order->getAllItems() as $item) {
$productArray[] = array(
"product_name" => $item->getName(),
"product_qty" => $item->getQtyOrdered(),
"product_price" => $item->getPrice(),
);
}
return $productArray;
}
here is my controller:
public function redirectAction(){
$session = Mage::getSingleton('checkout/session');
$session->setAsurepayCustompayQuoteId($session->getQuoteId());
$this->getResponse()->setBody($this->getLayout()->createBlock('custompay/redirect')->toHtml());
$session->unsQuoteId();
$session->unsRedirectUrl();
}
This are running perfectly running, the problem is i can't get customer details such as customer name, address and etc.
I already tried this code
Mage::getSingleton(customer/customer)->getData();
There was a result but not printing.
In the checkout page success (onepage). When customer redirected here, There is no email will be send to the customer and the order was not update as completed.
You're trying to load a customer with an id that belongs to the order. This obviously doesn't work! You need to extract the customer_id from the order and load the customer model based on that.
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
$customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
You're also using Mage::getSingleton which is the wrong call. You want a new instance tailored to a specific customer, not the single permissible instance of the class.

how to get payment information on Magento?

I have to export the orders to a file, here is my code to go through the orders:
$orders = Mage::getModel('sales/order')->getCollection()
->addAttributeToSelect(array('status', 'ncm'))
->addFieldToFilter(
array(
array('attribute' => 'status', 'eq' => 'complete')
)
);
$order = $orders->getFirstItem();
//print_r($order);
//exit;
//foreach($orders as $order){
$id = $order->getIncrementId();
$payment = $order->getPayment();
$method = $payment->getMethodInstance();
print_r($payment);
//}
I need to print some information about the payment
like the method, the amount, how many months it was split, if was credit card, i need the reutrning id of the transaction and so the list goes on
how can I do that?
I think it will be
$payment = $order->getPayment();
It will retrieve the current order payment instance.
//Get Payment
$payment = $order->getPayment()
//Get card type
$payment->getData('cc_type')
//Get Payment Info
$payment->getMethodInstance()->getCode();
$payment->getMethodInstance()->getTitle();
//Get Credit Card info
$payment->getMethodInstance()->getCardsStorage()
$payment->getMethodInstance()->getCardsStorage()->getCards() //array()
To get the method code only it's far safer to use
$order->getPayment()->getMethod();
Skipping instance object which can generate exception if the payment method was uninstalled.

Categories