This is my ChargifyCoupon.php
public function create($product_family_id = null, $details = []) {
$details = array_replace_recursive([
"name" => "15% off",
"code" => "15OFF",
"description" => "15% off for life",
"percentage" => "15",
"allow_negative_balance" => "false",
"recurring" => "false",
"end_date" => "2016-12-31T23:59:59-04:00",
"product_family_id" => $product_family_id
], $details);
$returnData = $this->connector->createCoupon($details, 'JSON');
var_dump($returnData);
die;
}
This is my ChargifyConnector.php
function createCoupon($product_family_id, $coupon_details = [], $format = 'XML') {
$extension = strtoupper($format) == 'XML' ? '.xml' : '.json';
$base_url = "/product_families/{$product_family_id}/coupons" . $extension;
$data = json_encode([
"coupon" => $coupon_details
]);
$coupon = $this->sendRequest($base_url, $format, 'POST', $data);
if ($coupon->code == 200) {
return $coupon->response;
} elseif ($coupon->code == 404 || $coupon->code == 500) {
var_dump($coupon);
die;
throw new \Exception($coupon->code, "Coupon was not created.");
}
}
When i'm trying to see result i'm getting "array to string conversion"
Sorry for late reply..
After so much research on chargify coupon,
simply remove /product_families/{$product_family_id}.
no need to send coupon data with product_families/{$product_family_id}.
For more details see HERE.
Updated Code :
function createCoupon($product_family_id, $coupon_details = [], $format = 'XML') {
$extension = strtoupper($format) == 'XML' ? '.xml' : '.json';
// $base_url = "/product_families/{$product_family_id}/coupons" . $extension;
$base_url = "/coupons" . $extension;
$data = json_encode([
"coupon" => $coupon_details
]);
$coupon = $this->sendRequest($base_url, $format, 'POST', $data);
if ($coupon->code == 200) {
return $coupon->response;
} elseif ($coupon->code == 404 || $coupon->code == 500) {
// var_dump($coupon);
// die;
throw new \Exception($coupon->code, "Coupon was not created.");
}
}
Related
I am trying to save images from dropbox to my server. I have already done the code for that. I am also checking the HTTP status of the url before downloading the images with code. I am getting proper status but the issue is it always throws an error 401 even when i have put a condition to download images with status code 200 or 302. I am having the links of images in an excel file that i am reading with a laravel package. Please help me.
Image Download Function
public function ImportImagesProcess(Request $request)
{
$product_type = $request->get('product_type');
$category_id = $request->get('category_id');
$category_level = $request->get('category_level');
$filepath = $request->get('file_path');
$total_rows = $request->get('total_rows');
$start_index = $request->get('start_index');
$row_counter_break = $request->get('row_counter_break');
$data = Excel::load($filepath)->limit(false, ($start_index))->get();
$dataArr = $data->toArray();
$array = array_map('array_filter', $dataArr);
$array = array_filter($array);
if ($start_index > $total_rows) {
return response()->json([
'status' => 'complete',
'product_type' => $product_type,
'category_id' => $category_id,
'category_level' => $category_level,
'file_path' => $filepath,
'total_rows' => $total_rows,
'start_index' => 0,
'row_counter_break' => $row_counter_break,
]);
} else {
$rowCounter = 0;
foreach ($array as $value) {
$image_list = [];
if (!empty($value['image1'])) {
array_push($image_list, $value['image1']);
}
if (!empty($value['image2'])) {
array_push($image_list, $value['image2']);
}
if (!empty($value['image3'])) {
array_push($image_list, $value['image3']);
}
if (!empty($value['image4'])) {
array_push($image_list, $value['image4']);
}
if (!empty($value['image5'])) {
array_push($image_list, $value['image5']);
}
foreach ($image_list as $il) {
if ($rowCounter >= $row_counter_break)
break;
$status = self::CheckLinkStatus($il);
if ($status == 200) {
if (strpos($il, "?dl=0") !== false) {
$image_url = str_replace("?dl=0", "", $il);
$image_url = str_replace("www.dropbox.com", "content.dropboxapi.com", $il);
$info = pathinfo($image_url);
$contents = file_get_contents($image_url, true);
$file = $info['basename'];
file_put_contents(public_path('datauploads') . "/" . $file, $contents);
} else {
$img_status = self::CheckLinkStatus($il);
if ($img_status !== 404 && $img_status !== 401) {
$image_url = str_replace("www.dropbox.com", "content.dropboxapi.com", $il);
$info = pathinfo($image_url);
$contents = file_get_contents($image_url, true);
$file = $info['basename'];
file_put_contents(public_path('datauploads') . "/" . $file, $contents);
}
}
}
}
$rowCounter++;
}
return response()->json([
'status' => 'success',
'product_type' => $product_type,
'category_id' => $category_id,
'category_level' => $category_level,
'file_path' => $filepath,
'total_rows' => $total_rows,
'start_index' => $start_index,
'row_counter_break' => $row_counter_break,
]);
}
}
Image Status Check Function
public static function CheckLinkStatus($image)
{
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $retcode;
}
Try this:
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpCode != 404) //# if error code is not "404"
{
/* Your Function here. */
}
else
{
/* Handle 404 here. */
}
Try setting an array of http codes, like:
$httpCodes = [401,404];
And than just check:
if(!in_array(CheckLinkStatus($image),$httpCodes){
// YOur logic
} else {
// Handle 401 && 404
}
i want to write a API for updating data in sql. I am using CI for it.I am new to this field.while i have written it is not working in localhost itself .Can anyone help me? I am attaching my controller and model here.it is showing an error like this page is not working
function editprofile($id,$data) {
$this->db->where(array('user_id' => $id));
$this->db->update('registrationdetails', $data);
if(!empty($id))
{
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$adminId = 1;
$AUTHENTIC_KEY = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$user_id=2;
$firstname ="aiswarya";
$lastname ="mathew";
$email ="aiswarya#gmail.com";
$password ="aiswarya";
$confirmpassword ="aiswarya";
$contactnumber ="999999999";
$gender ="female";
$address ="canada";
$department ="cse";
$designation ="swe";
$Admindetails = $this->common->CheckValidAdmin($adminId,$AUTHENTIC_KEY);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id
);
$data = array();
$data = array('firstname'=>$firstname,'lastname'=>$lastname,'email'=>$email,'password'=>$password,'confirmpassword'=>$confirmpassword,'contactnumber'=>$contactnumber,'gender'=>$gender,'address'=>$address,'department'=>$department,'designation'=>$designation);
$status = $this->user->editprofile($user_id,$data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
function editprofile($data) {
if(!empty($data['user_id']))
{
$this->db->where(array('user_id' => $data['user_id']));
$this->db->update('registrationdetails', $data);
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$data['adminId'] = 1;
$data['AUTHENTIC_KEY'] = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$data['user_id']=2;
$data['firstname'] ="aiswarya";
$data['lastname'] ="mathew";
$data['email'] ="aiswarya#gmail.com";
$data['password'] ="aiswarya";
$data['confirmpassword'] ="aiswarya";
$data['contactnumber'] ="999999999";
$data['gender'] ="female";
$data['address'] ="canada";
$data['department'] ="cse";
$data['designation'] ="swe";
$Admindetails = $this->common->CheckValidAdmin($data['adminId'],$data['AUTHENTIC_KEY']);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id);
$status = $this->user->editprofile($data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
I have a Laravel 5.4 project. There is a route issue that i can't solve second day.
I have two routes like:
Route::get('/', 'HomeController#index')->name('index');
public function index(CookieJar $cookieJar, Request $request)
{
// Берем город из куков
$city_from_cookie = Cookie::get('city');
// Если города нет в куках
if (!$city_from_cookie) {
$client = new Client();
$ip = $request->ip() == '127.0.0.1' ? '95.85.70.7' : $request->ip();
$json = $client->request('GET', 'http://freegeoip.net/json/' . $ip . '');
$city = json_decode($json->getBody()->getContents());
if ($city->city === null) {
$cookie = cookie('city', config('custom.city.default_slug'), 21600, null, null, false, true);
$cookieJar->queue($cookie);
$city = config('custom.city.default_slug');
} else {
$city = strtolower($city->city);
try {
$city = City::findBySlugOrFail($city);
$city = $city->slug;
} catch (ModelNotFoundException $ex) {
$city = 'moskva';
}
$cookie = cookie('city', $city, 21600, null, null, false, false);
$cookieJar->queue($cookie);
}
} else {
$city = $city_from_cookie;
}
return redirect(route('city', [$city]), 301);
}
AND
Route::get('{city}', 'HomeController#getCityCategories')->name('city');
public function getCityCategories(City $city, CookieJar $cookieJar)
{
// Cache::flush();
// dd(request()->getRequestUri());
$cookie = cookie('city', $city->slug, 21600, null, null, false, false);
$cookieJar->queue($cookie);
$categories = Category::whereNull('parent_id')->with('subcategories')->get();
if ($city->weather_id) {
$weather = $this->getWeather($city->weather_id);
} else {
$weather = [
'city' => '',
'temp_min' => '',
'temp_max' => '',
'day' => '',
'symbol' => '',
'symbol_desc' => ''
];
}
return view('pages.categories', compact('categories', 'city', 'weather'));
}
The problem is that if you go to the '/' root first time method will do it's work but when you're getting the city like /moskva and if you change your city with another for example /abakan and then go the root '/' you will be redirected to the /moskva. I tried almost everything, turned off any cahing, cleared cache with artisan commands but it does not helped. Here is domain for testing this issue: okololo.ru
I try to made a telegram bot, but I've a problem when I send a photo.
This is my code:
I have this function:
function apiRequestImage($method, $parameters)
{
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$urlpath = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($urlpath);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
}
and this to call it
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
$img = curl_file_create('test.png','image/png');
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi','Bye')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if ($text === "Bye") {
apiRequestImage("sendPhoto", array('chat_id' => $chat_id, 'photo' => '#'.$img));
}else if (strpos($text, "/stop") === 0) {
// stop now
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
}
} else {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
}
}
and call all
if (isset($update["message"])) {
processMessage($update["message"]);
}
The text run, but the photo no.
Can you help me?
The rest of code: http://pastebin.com/BKPxe2KC
Your code has multiple parts. I recommend that test part by part,
For example, your function has keyboard part and it seems not working(bad Telegram syntax), and it can prevent other parts(like photo sending). In my opinion it is better you first work on just on thing(for example sending photo) and when it did its job best then go on and add keyboard.(This is a working keyboard code https://stackoverflow.com/a/37948952/6478645.
I'm currently implementing smartrecruiter api in my project. I'm using two endpoints namely /jobs-list and /job-details. The problem is that every time I'm extracting the details in the second endpoint which is the /job-details, the execution time is so slow.
Here's what I've done so far:
function getContext()
{
$opts = array(
'http'=> array(
'method' => 'GET',
'header' => 'X-SmartToken: xxxxxxxxxxxxxxxxx'
)
);
return $context = stream_context_create($opts);
}
function getSmartRecruitmentJob($city, $department)
{
$tmp = array();
$results= array();
$limit = 100; //max limit for smartrecruiter api is 100
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs?limit='.$limit.'&city='.$city.'&department='.$department, false, $this->getContext());
$lists= json_decode($file, true);
foreach($lists['content'] as $key => $list)
{
if ($list['status'] == 'SOURCING' || $list['status'] == 'INTERVIEW' || $list['status'] == 'OFFER')
{
$results['id'] = $list['id'];
$tmp[] = $this->getSmartRecruitmentJobDetails($results['id']);
}
}
return $tmp;
}
function getSmartRecruitmentJobDetails($id)
{
$results = array();
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}
Solved it by caching the function for extracting the data:
function getCache()
{
if ($this->cache === null)
{
$cache = \Zend\Cache\StorageFactory::factory(
array(
'adapter' => array(
'name' => 'filesystem',
'options' => array(
'ttl' => 3600 * 7, // 7 hours
'namespace' => 'some-namespace',
'cache_dir' => 'your/cache/directory'
),
),
'plugins' => array(
'clear_expired_by_factor' => array('clearing_factor' => 10),
),
)
);
$this->cache = $cache;
}
return $this->cache;
}
function getSmartRecruitmentJobDetails($id)
{
$cache = $this->getCache();
$key = md5('https://api.smartrecruiters.com/jobs/'.$id);
$lists = unserialize($cache->getItem($key, $success));
$results = array();
if($success && $lists)
{
header('Debug-cache-recruit: true');
}
else
{
header('Debug-cache-recruit: false');
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$cache->addItem($key, serialize($lists));
}
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country'] = isset($lists['location']['country']) ? $lists['location']['country'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}