I try create signature to delete photo follow code below.
$args = array(
'method' => 'flickr.photos.delete',
'format' => 'php_serial',
'api_key' => $this->api_key,
'photo_id' => $photoId,
'auth_token' => $this->token,
);
ksort($args);
$auth_sig = "";
foreach ($args as $key => $data) {
if ( is_null($data) ) {
unset($args[$key]);
continue;
}
$auth_sig .= $key . $data;
$api_sig = md5($this->secret . $auth_sig);
}
But when I use signature for api flickr.photos.delete I got message Invalid signature although I still upload and replace image success.
This is code call api flickr.photos.delete,
$params = array(
'method' => 'flickr.photos.delete',
'format' => 'php_serial',
'api_key' => $this->api_key,
'photo_id' => $photoId,
'auth_token' => $this->token,
'perms' => 'write',
'api_sig' =>$api_sig
);
$encoded_params = array();
foreach ($params as $k => $v){
$encoded_params[] = urlencode($k).'='.urlencode($v);
}
$url = $this->rest_endpoint."?".implode('&', $encoded_params);
$rsp = file_get_contents($url);
$rsp_obj = unserialize($rsp);
var_dump($rsp_obj);
How can I resolve this problem?
Related
Please am trying to upload 3 different images using the code below. How do I get each of the methods that generates the unique image names to run only when their respective request fields have data or is not empty. thus the form submit should not try generating any image name for afile field when that particular file field is empty.
My update controller function
public function update(Request $request, Product $product)
{
$image = $request->file('primary_image');
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$image_1 = $request->file('image_1');
$name_gen = md5(rand(1000, 10000)).'.'.$image_1->getClientOriginalExtension();
Image::make($image_1)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_1 = 'upload/products/'.$name_gen;
$image_2 = $request->file('image_2');
$name_gen = md5(rand(1000, 10000)).'.'.$image_2->getClientOriginalExtension();
Image::make($image_2)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_2 = 'upload/products/'.$name_gen;
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'image_1' => $save_url_1,
'image_2' => $save_url_2,
]);
$notification = array(
'message' => 'Product updated successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Thanks so much for taking time to review my code
Since you are doing the same name generation process all through, you can use an array and do a foreach loop with an if condition like this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
foreach($my_array as $item) {
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
}
Now this will only generate names for images that are not empty.
UPDATE:
For the insert functionality, I would assume your table fields for the images can have null values, so this doesn't throw an error. Now instead of the code above, do this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
$insert_array = [];
foreach($my_array as $item) {
$save_url = '';
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
array_push($insert_array, $save_url);
}
Now for your insert query, do this:
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $insert_array[0],
'image_1' => $insert_array[1],
'image_2' => $insert_array[2],
]);
This would work.
I have a function on my site that creates a promo code for an affiliate automatically once every 24 hours. If 24 hours have passed since the creation of the promo code, it is deleted old promo from the database, and a new one is generated anew. But now there is a problem with this function, it generates a new promo code every time, regardless of whether 24 hours have passed or not.
My function:
public function autoGroupPromos()
{
$userList = Promo::get();
$userIds = $userList->pluck('user_id');
foreach ($userIds as $id) {
$date = Carbon::now();
$promoCodes = Promocode::query()->where('vk_user_id', '!=', null)->get();
foreach ($promoCodes as $promos) {
// If promo create 24 hours ago
$hours = $promos->created_at->diffInHours($date);
if ($hours >= 24) {
$promos->delete();
}
}
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$code = substr(str_shuffle($permitted_chars), 0, 8);
Promocode::query()->create([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
'vk_user_id' => $id
]);
$promoText = Promocode::where('vk_user_id', $id)->orderBy('created_at', 'desc')->first();
$promoName = $promoText->name;
$message = 'Your new promo: ' . $promoName . ';
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
}
}
That is, if less than 24 hours have passed since the promo was created - it should not be deleted and a new promo code should not be generated. But now unfortunately there is an error somewhere.
What can be the problem?
function autoGroupPromos()
{
// removed for loop to clean outdated promos in single request
// note that this way of deleting rows won't fire model events (if any)
Promocode::whereNotNull('vk_user_id')
->where('created_at', '<=', Carbon::now()->subDay(1))
->delete();
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$userIds = Promo::pluck('user_id');
foreach ($userIds as $id) {
/* in the begining we cleaned all outdated codes, so if user still has
some - no need to create new */
if (Promocode::where('vk_user_id', $id)->exists()){
continue;
}
$code = substr(str_shuffle($permitted_chars), 0, 8);
/* you can immidiately get create model like this -
no need to make another request
$createdPromo = Promocode::create([*/
Promocode::create([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
'vk_user_id' => $id
]);
/* didn't get why you were requesting newly created
promo to get name field if you put there $code value */
$message = `Your new promo: $code`;
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
}
}
upd: here can be a bit cleaner way with hasOneOfMany and skipping each user request to check if promocode exists
// User model
public function promocodes() {
return $this->hasMany(Promocode::class);
}
public function promocode() {
return $this->hasOne(Promocode::class)->latestOfMany();
}
function autoGroupPromos()
{
// note that this way of deleting rows won't fire model events (if any)
Promocode::whereNotNull('vk_user_id')
->where('created_at', '<=', Carbon::now()->subDay(1))
->delete();
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
// taking users without promo after cleanup
User::whereDoesntHave('promo')->get()
->each(function (User $user) use ($permitted_chars) {
$code = substr(str_shuffle($permitted_chars), 0, 8);
// pay attention on relation name - using hasMany
$user->promocodes()->save(
new Promocode([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
])
);
$message = `Your new promo: $code`;
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
});
}
link Inserting & Updating Related Models
I am trying to send a request to RingCentral API. The link to documentation is https://developers.ringcentral.com/api-reference/Fax/createFaxMessage If I don't specify faxResolution or coverIndex everything goes well, fax could be sent. But if I add faxResolution param like in the code below, I receive error "Parameter [faxResolution] value is invalid", "errorCode" : "CMN-101". The same thing with coverIndex param. My client is GuzzleHttp 6.3
$token = $this->ringcentral->platform()->auth()->data()['access_token'];
$a = array();
foreach ($destination_numbers as $number) {
$a[] = [
'name' => 'to',
'contents' => $number,
'headers' => ['Content-Type' => 'multipart/form-data']
];
}
$a[] = [
'name' => 'faxResolution',
'contents' => 'High',
'headers' => ['Content-Type' => 'multipart/form-data']
];
foreach ($attachments as $attachment) {
$file_pointer = fopen($attachment, 'r');
$mime = mime_content_type($attachment);
$a[] = [
'name' => 'attachment',
'contents' => $file_pointer,
'headers' => ['Content-Type' => $mime]
];
}
$client = new Client();
try {
$response = $client->request('POST', url(config('services.ringcentral.app_url')) . '/restapi/v1.0/account/~/extension/~/fax', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'multipart' => $a
]);
$response = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
echo($e->getResponse()->getBody()->getContents());
}
Here's what RingCentral suggests when using PHP. I included all of what they suggested, but just look at the part about faxResolution (2/3 of the way down)
<?php
// https://developers.ringcentral.com/my-account.html#/applications
// Find your credentials at the above url, set them as environment variables, or enter them below
// PATH PARAMETERS
$accountId = '<ENTER VALUE>';
$extensionId = '<ENTER VALUE>';
$recipient = '<ENTER VALUE>';
require('vendor/autoload.php');
$rcsdk = new RingCentral\SDK\SDK(getenv('clientId'), getenv('clientSecret'), getenv('serverURL'));
$platform = $rcsdk->platform();
$platform->login(getenv('username'), getenv('extension'), getenv('password'));
$request = $rcsdk->createMultipartBuilder()
->setBody(array(
'to' => array(array('phoneNumber' => $recipient)),
'faxResolution' => 'High',
))
->add(fopen('fax.jpg', 'r'))
->request("/restapi/v1.0/account/{$accountId}/extension/{$extensionId}/fax");
$r = $platform->sendRequest($request);
?>
require_once('modules/FedEx/RateAvailableServicesService_v18_php/library/fedex-common.php5');
$path_to_wsdl = PATH."modules/FedEx/RateAvailableServicesService_v18_php/RateService_v18.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
//'ParentCredential' => array(
//'Key' => $this->getProperty('key'),
//'Password' => $this->getProperty('password')
//),
'UserCredential' => array(
'Key' => $this->getProperty('key'),
'Password' => $this->getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => $this->getProperty('shipaccount'),
'MeterNumber' => $this->getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '18',
'Intermediate' => '0',
'Minor' => '1'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
// Service Type and Packaging Type are not passed in the request
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['Shipper'] = array(
'Address'=> array('StreetLines' => array($UL->str_add1,$UL->str_add2),'City' => $UL->city_name,'StateOrProvinceCode' => $UL->state_name,'PostalCode' => $UL->zipcode,'CountryCode' => $UL->country_code));
$request['RequestedShipment']['Recipient'] = array(
'Address'=>array('StreetLines' => array($this->session->get('shipping_address1'),$this->session->get('shipping_address2')),'City' => $shipping_city,'StateOrProvinceCode' => $shipping_state,'PostalCode' => $this->session->get('shipping_postal_code'),'CountryCode' => $country_code,'Residential' => false));
$request['RequestedShipment']['ShippingChargesPayment'] = array(
'PaymentType' => 'SENDER',
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => $this->getProperty('billaccount'),
'Contact' => null,
'Address' => array(
'CountryCode' => COUNTRY_CODE
)
)
)
);
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = array(
'0' => array(
'SequenceNumber' => 1,
'GroupPackageCount' => 1,
'Weight' => array(
'Value' => $UL->weight//,
//'Units' => 'LB'
),
'Dimensions' => array(
'Length' => $UL->length,
'Width' => $UL->width,
'Height' => $UL->height//,
//'Units' => 'IN'
)
)
);
try {
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
echo 'Rates for following service type(s) were returned.'. Newline. Newline;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td>';
if(is_array($response -> RateReplyDetails)){
foreach ($response -> RateReplyDetails as $rateReply){
$this->printRateReplyDetails($rateReply);
}
}else{
$this->printRateReplyDetails($response -> RateReplyDetails);
}
echo '</table>'. Newline;
printSuccess($client, $response);
}else{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
Here is error exception which i am getting
Fault
Code:SOAP-ENV:Server
String:Fault
Request
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v18"><SOAP-ENV:Body><ns1:RateRequest><ns1:WebAuthenticationDetail><ns1:UserCredential><ns1:Key>AndJurrJfCvvWZWn</ns1:Key><ns1:Password>Rps8Pl4jF9zGp5wiEpDRhKiHo</ns1:Password></ns1:UserCredential></ns1:WebAuthenticationDetail><ns1:ClientDetail><ns1:AccountNumber>631140688</ns1:AccountNumber><ns1:MeterNumber>107714405</ns1:MeterNumber></ns1:ClientDetail><ns1:TransactionDetail><ns1:CustomerTransactionId> *** Rate Available Services Request using PHP ***</ns1:CustomerTransactionId></ns1:TransactionDetail><ns1:Version><ns1:ServiceId>crs</ns1:ServiceId><ns1:Major>18</ns1:Major><ns1:Intermediate>0</ns1:Intermediate><ns1:Minor>1</ns1:Minor></ns1:Version><ns1:ReturnTransitAndCommit>true</ns1:ReturnTransitAndCommit><ns1:RequestedShipment><ns1:ShipTimestamp>2016-03-30T18:35:41+05:30</ns1:ShipTimestamp><ns1:DropoffType>REGULAR_PICKUP</ns1:DropoffType><ns1:ServiceType>INTERNATIONAL_PRIORITY</ns1:ServiceType><ns1:Shipper><ns1:Address><ns1:StreetLines>SUITE 5A-1204</ns1:StreetLines><ns1:StreetLines>799 E DRAGRAM</ns1:StreetLines><ns1:City>TUCSON</ns1:City><ns1:StateOrProvinceCode>AZ</ns1:StateOrProvinceCode><ns1:PostalCode>94040</ns1:PostalCode><ns1:CountryCode>US</ns1:CountryCode></ns1:Address></ns1:Shipper><ns1:Recipient><ns1:Address><ns1:StreetLines>795 E</ns1:StreetLines><ns1:StreetLines>DRAGRAM</ns1:StreetLines><ns1:City>TUCSON</ns1:City><ns1:StateOrProvinceCode>AZ</ns1:StateOrProvinceCode><ns1:PostalCode>94040</ns1:PostalCode><ns1:CountryCode>US</ns1:CountryCode><ns1:Residential>false</ns1:Residential></ns1:Address></ns1:Recipient><ns1:ShippingChargesPayment><ns1:PaymentType>SENDER</ns1:PaymentType><ns1:Payor><ns1:ResponsibleParty><ns1:AccountNumber>631140688</ns1:AccountNumber><ns1:Address><ns1:CountryCode>KWI</ns1:CountryCode></ns1:Address></ns1:ResponsibleParty></ns1:Payor></ns1:ShippingChargesPayment><ns1:PackageCount>1</ns1:PackageCount><ns1:RequestedPackageLineItems><ns1:SequenceNumber>1</ns1:SequenceNumber>
<ns1:GroupPackageCount>1</ns1:GroupPackageCount><ns1:Weight>
<ns1:Value>20</ns1:Value></ns1:Weight><ns1:Dimensions>
<ns1:Length>8</ns1:Length><ns1:Width>10</ns1:Width>
<ns1:Height>10</ns1:Height></ns1:Dimensions></ns1:RequestedPackageLineItems>
</ns1:RequestedShipment></ns1:RateRequest></SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Since you have trace on, you should look at the actual request/response data. When I took your raw POST data above (in which you shouldn't have posted your account/key info) I get back a schema validation error. Syntax looks correct but the country code for payor is KWI but should be US. I'd suggest you add some code to log the request and responses...
$soap_response_hdr = $client->__getLastResponseHeaders() ;
$soap_response = $client->__getLastResponse() ;
$soap_request_hdr = $client->__getLastRequestHeaders() ;
$soap_request = $client->__getLastRequest() ;
I sent request to webservice like this :
$transaction = new Transaction();
$transaction->amount = $amount;
$transaction->order_id = $orderId;
$transaction->status = 0;
$transaction->additional_data = $additionalData;
$transaction->type = 1;
$transaction->ip = Request::getClientIp();
$transaction->save();
$soap = new nusoap_client(self::$request_url);
$fields = array(
'terminalId' => self::$terminalId,
'userName' => self::$username,
'userPassword' => self::$password,
'orderId' => $transaction->order_id,
'amount' => $amount,
'localDate' => date('Ymd'),
'localTime' => date('His'),
'additionalData' => $additionalData,
'callBackUrl' => self::$callBackUrl,
'payerId' => 0,
);
$response = $soap->call('bpPayRequest', $fields, 'http://interfaces.core.sw.bps.com/');
but i get exception in line 2125 in nusoap.php :
Array to string conversion
exception thrown from :
// TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
foreach(curl_getinfo($this->ch) as $k => $v){
$err .= "$k: $v<br>";
}
$this->debug($err);