Google Drive File not set expiration time permissions - php

$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress($value);
$newPermission->setExpirationTime('2018-07-13T16:00:00+05:30');
$newPermission->setType($type);
$newPermission->setRole($role);
my drive storage not storing ExpirationTime

There is some minor changes in v3. Check out this links https://developers.google.com/drive/api/v3/reference/permissions/create https://developers.google.com/drive/api/v3/manage-sharing
https://gist.github.com/bshaffer/9bb2cdccd315880ab52f#file-drive-php-L954
insertPermission($service, $fileId, $value, $type, $role) {
$newPermission = new Google_Service_Drive_Permission(array(
'type' => $type,
'role' => $role,
'emailAddress' => $value,
'expirationTime' => '2018-08-18T16:00:00+05:30'
));
try {
$created = $service->permissions->create($fileId, $newPermission);
$permissionsId = $created->id;
$updatedPermission = new Google_Service_Drive_Permission(array(
'role' => $role,
'expirationTime' => '2018-08-18T16:00:00+05:30'
));
$updated = $service->permissions->update($fileId, $permissionsId , $updatedPermission, array(
'fields' => 'id, expirationTime'
));
$expirationTime = $updated->expirationTime;
echo "expirationTime : " . $expirationTime;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}

Related

Stripe Checkout from Legacy to new migration not working

I have migrated my Stripe checkout from legacy version to the new one. The payment does work, but the success redirect URL as well as the DB update does not work.
When I send the request I get redirected to my main page instead of the user subscription page.
Also I do get the error:
Could not determine the URL to request: StripeCustomer instance has invalid ID: (no ID)
I already did some research and also visited the migration documentation from Stripe:
https://stripe.com/docs/payments/checkout/migration
But I do not get the error.
My guess is it is between the lines:
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
from:
<?php
namespace App\Http\Controllers\Frontend\Gateways;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Frontend\User\CheckoutController;
use Exception;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Customer;
use Stripe\Stripe;
class StripeCheckoutController extends Controller
{
public static function process($trx)
{
if ($trx->status != 0) {
$data['error'] = true;
$data['msg'] = lang('Invalid or expired transaction', 'checkout');
return json_encode($data);
}
if ($trx->plan->interval == 0) {
$planInterval = '(Monthly)';
} elseif ($trx->plan->interval == 1) {
$planInterval = '(Yearly)';
} elseif ($trx->plan->interval == 2) {
$planInterval = '(Lifetime)';
}
$paymentName = "Payment for subscription " . $trx->plan->name . " Plan " . $planInterval;
$gatewayFees = ($trx->total_price * paymentGateway('stripe_checkout')->fees) / 100;
$totalPrice = round(($trx->total_price + $gatewayFees), 2);
$priceIncludeFees = str_replace('.', '', ($totalPrice * 100));
$paymentDeatails = [
'customer_email' => $trx->user->email,
'payment_method_types' => [
'card',
],
'line_items' => [[
'price_data' => [
'currency' => currencyCode(),
'unit_amount' => $priceIncludeFees,
'product_data' => [
'name' => settings('website_name'),
'description' => $paymentName,
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'cancel_url' => route('user.subscription'),
'success_url' => route('ipn.stripe_checkout') . '?session_id={CHECKOUT_SESSION_ID}',
];
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$session = Session::create($paymentDeatails);
if ($session) {
$trx->update(['fees_price' => $gatewayFees, 'payment_id' => $session->id]);
$data['error'] = false;
$data['redirectUrl'] = $session->url;
return json_encode($data);
}
} catch (\Exception $e) {
$data['error'] = true;
$data['msg'] = $e->getMessage();
return json_encode($data);
}
}
public function ipn(Request $request)
{
$session_id = $request->session_id;
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$trx = \App\Models\Transaction::where([['user_id', userAuthInfo()->id], ['payment_id', $session_id], ['status', 1]])->first();
if (is_null($trx)) {
throw new Exception(lang('Invalid or expired transaction', 'checkout'));
}
$session = Session::retrieve($session_id);
//if ($session->payment_status == "paid") {
if ($session->payment_status == "paid") {
$customer = Customer::retrieve($session->customer);
$total = ($trx->total_price + $trx->fees_price);
$payment_gateway_id = paymentGateway('stripe_checkout')->id;
$payment_id = $session->id;
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
} else {
throw new Exception(lang('Payment failed', 'checkout'));
}
} catch (\Exception $e) {
toastr()->error($e->getMessage());
return redirect()->route('home');
}
}
}

"INVALID_ARGUMENT" when updating or adding a label using the gmail api

I am trying to manage the mail labels using the gmail api the delete does but when I try to add or modify some it tells me that the arguments are invalid.
My code to modify is the following:
public function editLabelGmail(Request $request)
{
try {
$url = 'https://www.googleapis.com/gmail/v1/users/me/labels';
$token = LaravelGmail::getToken()['access_token'];
$params = [
'id' => $request->id,
'labelListVisibility' => 'labelShow',
'messageListVisibility' => 'show',
'name' => $request->name,
];
$response = Http::asForm()
->put(
$url . '/' . $request->id . '?access_token=' . $token,
$params
)
->json();
return Response($response, 200);
} catch (\Exception $e) {
return Response()->json(
[
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
],
500
);
}
}
And to add:
public function addLabelGmail(Request $request)
{
try {
$url = 'https://gmail.googleapis.com/gmail/v1/users/me/labels';
$token = LaravelGmail::getToken()['access_token'];
$params = [
'labelListVisibility' => 'labelShow',
'messageListVisibility' => 'show',
'name' => $request->name,
'type' => 'user',
];
$response = Http::asForm()
->post($url . '?access_token=' . $token, $params)
->json();
return Response([$response, 'ok'], 200);
} catch (\Exception $e) {
return Response()->json(
[
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
],
500
);
}
}
The parameters I am passing from the front end are coming in as follows:
{
"id": "Label_3",
"name": "Test3"
}
Solution:
I was able to solve it by replacing the $response with the following:
Method Add:
$response = Http::post($url . '?access_token=' . $token, $params)->json();
Method Update:
$response = Http::put($url . '?access_token=' . $token, $params)->json();

How to get multiple images in laravel api?

I am creating a laravel API for complaints. This code is not saving multiple images in the database and I have to show multiple images in JSON response in an array. I am using array_get but it's not working for me. I have tried many things but it is not saving images in database. I have no idea. I am saving images in other table.
public function Complains(Request $request)
{
$response = array();
try {
$allInputs = Input::all();
$userID = trim($request->input('user_id'));
$cordID = trim($request->input('cord_id'));
$phone = trim($request->input('phone'));
$address = trim($request->input('address'));
$description = trim($request->input('description'));
// $image = array_get($allInputs, 'image');
$validation = Validator::make($allInputs, [
'user_id' => 'required',
'cord_id' => 'required',
'phone' => 'required',
'address' => 'required',
'description' => 'required',
]);
if ($validation->fails()) {
$response = (new CustomResponse())->validatemessage($validation->errors()->first());
} else {
$checkRecord = User::where('id', $userID)->get();
if (count($checkRecord) > 0) {
$complainModel = new Complains();
$complainModel->user_id = $userID;
$complainModel->cord_id = $cordID;
$complainModel->phone_no = $phone;
$complainModel->address = $address;
$complainModel->description = $description;
$saveData = $complainModel->save();
if ($saveData) {
if ($request->file('image')) {
$path = 'images/complain_images/';
// return response()->json(['check', 'In for loop']);
foreach ($request->file('image') as $image) {
$imageName = $this->uploadImage($image, $path);
$ImageSave = new ComplainImages();
$ImageSave->complain_id = $complainModel->id;
$ImageSave->image_url = url($path . $imageName);
$ImageSave->save();
}
}
$jsonobj = array(
'id' => $userID,
'name' => $cordID,
'email' => $phone,
'phone' => $address,
'description' => $description,
);
return Response::json([
'Exception' => "",
'status' => 200,
'error' => false,
'message' => "Complain Registered Successfully",
'data' => $jsonobj
]);
}
}else{
$response = (new CustomResponse())->failResponse('Invalid ID!');
}
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new CustomResponse())->queryexception($ex);
}
return $response;
}
public function uploadImage($image, $destinationPath)
{
$name = rand() . '.' . $image->getClientOriginalExtension();
$imageSave = $image->move($destinationPath, $name);
return $name;
}
There is a mistake in looping allImages. To save multiple images try below code
foreach($request->file('image') as $image)
{
$imageName = $this->uploadImage($image, $path);
// other code here
}
Check if you are reaching the loop
return response()->json(['check': 'In for loop'])

Amazon S3 Multiple Part Upload Returns NULL

I am trying to upload an 8GB file, but it constantly returns null. I also do not get an error message no exceptions thrown. The null is displayed in the va_dump, the normal s3 -> putObject works fine with files under 5GB. My code is the following:
$s3 = S3Client::factory(array(
'credentials' => array(
'secret' => 'xxx',
'key' => 'xxxxx'
),
'region' => 'us-west-2',
'version' => '2006-03-01'
));;
try {
if(filesize($body) < 5000000000) {
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $obect,
'SourceFile' => $body,
'ContentType' => $content_type,
'ACL' => $acl,
));
return $result['ObjectURL'];
} else {
echo 'Starting Uploads';
$source = fopen($body, 'rb');
$uploader = new MultipartUploader($s3, $source
, [
'bucket' => $bucket,
'key' => $obect,
'acl' => $acl,
'concurrency' => 5,
'part_size' => (100 * 1024 * 1024),
'before_initiate' => function(\Aws\Command $command) use ($content_type) {
$command['ContentType'] = $content_type; // video/mp4
}
]);
echo 'Into Upload';
$result = $uploader->upload();
echo 'Complete Upload';
var_dump($result);
return (isset($result['Location'])) ? $result['Location'] : false;
}
} catch (MultipartUploadException $e) {
error_log($e -> getMessage() . ' ' . $e -> getTraceAsString());
$uploader = new \Aws\S3\MultipartUploader($s3, $body, [
'state' => $e->getState(),
]);
return false;
} catch (Aws\Exception\S3Exception $e) {
error_log($e -> getMessage() . ' ' . $e -> getTraceAsString());
return false;
} catch (Exception $e) {
error_log($e -> getMessage() . ' ' . $e -> getTraceAsString());
return false;
}
return false;

Magento image upload filename doesn't save in database

I am trying to add an additional image upload field to a gallery extension. The code for the extension controller is below. I've added an extra column to the database called galpic_popup_image with the same values as the existing galpic_image column.
I've managed to get the upload working, so images are saved on the server, however it isn't saving the filename in the database and therefore I can't call it on the frontend.
class ParadoxLabs_Gallery_Adminhtml_GalleryController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
$this->loadLayout();
$this->_setActiveMenu('cms/gallery');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Gallery'), Mage::helper('adminhtml')->__('Gallery'));
$this->renderLayout();
}
public function editAction()
{
$this->loadLayout();
$this->_setActiveMenu('cms/gallery');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Gallery'), Mage::helper('adminhtml')->__('Gallery'));
$this->_addContent($this->getLayout()->createBlock('gallery/adminhtml_gallery_edit'));
$this->renderLayout();
}
public function newAction()
{
$this->editAction();
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
// Image uploading code modified from https://magento2.atlassian.net/wiki/spaces/m1wiki/pages/14024884/How+to+create+an+image+or+video+uploader+for+the+Magento+Admin+Panel
if(isset($_FILES['image']['name']) && (file_exists($_FILES['image']['tmp_name'])))
{
try{
$uploader = new Varien_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'p_gallery' . DS ;
$uploader->save($path, $_FILES['image']['name']);
$data['image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'p_gallery/'. $_FILES['image']['name'];
}catch(Exception $e){}
}
else
{
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1){
$data['image_main'] = '';
}
else{
unset($data['image']);
}
}
if(isset($_FILES['popup_image']['name']) && (file_exists($_FILES['popup_image']['tmp_name'])))
{
try{
$uploader = new Varien_File_Uploader('popup_image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'p_gallery' . DS ;
$uploader->save($path, $_FILES['popup_image']['name']);
$popupdata['popup_image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'p_gallery/'. $_FILES['popup_image']['name'];
}catch(Exception $e){}
}
else
{
if(isset($popupdata['fileinputname']['delete']) && $popupdata['fileinputname']['delete'] == 1){
$popupdata['popup_image_main'] = '';
}
else{
unset($popupdata['popup_image']);
}
}
try {
if( intval($this->getRequest()->getParam('id')) == 0 ) { // New
$model = Mage::getModel('gallery/gallery')
->setGalpicId ( $this->getRequest()->getParam('id') )
->setGalpicStore( $this->getRequest()->getParam('store') )
->setGalpicDate ( date('Y-m-d', time()) )
->setGalpicName ( $this->getRequest()->getParam('name') )
->setGalpicImage( $data['image'] )
->setGalpicPopupImage( $popupdata['popup_image'] )
->save();
}
else { // Edit
$model = Mage::getModel('gallery/gallery')
->setGalpicId ( $this->getRequest()->getParam('id') )
->setGalpicStore( $this->getRequest()->getParam('store') )
->setGalpicName ( $this->getRequest()->getParam('name') )
->setGalpicImage( $data['image'] )
->setGalpicPopupImage( $popupdata['popup_image'] )
->save();
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Galpic was successfully saved'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$model = Mage::getModel('gallery/gallery');
$model->setGalpicId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Galpic was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
protected function _isAllowed()
{
return Mage::getSingleton('admin/session')->isAllowed('cms/gallery');
}
}
And here is the form used to capture the data:
class ParadoxLabs_Gallery_Block_Adminhtml_Gallery_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
}
}
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'enctype' => 'multipart/form-data',
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
));
$fieldset = $form->addFieldset('gallery_form', array(
'legend' => Mage::helper('gallery')->__('Galpic'),
'class' => 'fieldset-wide'
)
);
$fieldset->addField('galpic_name', 'text', array(
'name' => 'name',
'label' => Mage::helper('gallery')->__('Name'),
'class' => 'required-entry',
'required' => true,
));
$fieldset->addField('galpic_image', 'image', array(
'name' => 'image',
'label' => Mage::helper('gallery')->__('Image'),
'class' => 'required-entry',
'required' => true,
));
$fieldset->addField('galpic_popup_image', 'image', array(
'name' => 'popup_image',
'label' => Mage::helper('gallery')->__('Popup Image'),
'class' => 'required-entry',
'required' => true,
));
$fieldset->addField('galpic_store', 'select', array(
'name' => 'store',
'label' => Mage::helper('core')->__('Store View'),
'title' => Mage::helper('core')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
));
if (Mage::registry('gallery')) {
$form->setValues(Mage::registry('gallery')->getData());
}
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
Ok, I fixed it!
It was suggested to make sure the columns were in the same order as the controller saves the items so I did that. It didn't seem to have an effect (but it may have done).
I changed the second image upload code to the following (basically removed 'popup' from $popupdata as Kiatng suggested) above:
if(isset($_FILES['popup_image']['name']) && (file_exists($_FILES['popup_image']['tmp_name'])))
{
try{
$uploader = new Varien_File_Uploader('popup_image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'p_gallery' . DS ;
$uploader->save($path, $_FILES['popup_image']['name']);
$data['popup_image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'p_gallery/'. $_FILES['popup_image']['name'];
}catch(Exception $e){}
}
else
{
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1){
$data['image_main'] = '';
}
else{
unset($data['popup_image']);
}
}

Categories