I have this code I have written and tested. The first phase
mokkle_test(Request $request)
is working. I have issue with how to pass the result of the request to the second phase
First phase:
public function mokkle_test(Request $request)
{
$telco_match=['name'=>'Icell'];
$telco=Telco::where($telco_match)->first();
try{
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' =>$request->text,
'correlator' =>$request->correlator,
'serviceid' =>$request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$noti=new Notification_log();
$noti->error_message= (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
}catch(\Exception $e)
{
return $e->getMessage();
}
}
... and its working very well.
How do I pass the result of the response into another function shown below.
Second phase:
function subscribe($request,$telco)
{
try{
$client = new Client();
$response = $client->request(
'POST', $telco->billing_callback_2, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->password,
'amount' =>$request->amount,
'shortcode' => $request->shortcode
],
'headers' => [
'auth' => $telco->authorization,
'key' => $telco->key,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$amount = $request->amount;
$shortcode = $request->shortcode;
$noti=new Notification_log();
$noti->error_message=(string)$response;
$noti->msisdn=$request->msisdn;
$noti->product_id=$request->productid;
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
$request = array();
$request->text= "Weldone";
$request->amount = $amount;
$request->serviceid="100010";
$request->correlator="876543ghj";
$result_sms=self::mokkle_test($request);
return $result;
}catch(\Exception $e)
{
return $e;
}
}
I tried this, but nothing is happening
$result_sms=self::mokkle_test($request);
Kindly assist. How do I achieve my goal. Kindly assist me.
Here you can pass it to the other method
public function mokkle_test(Request $request)
{
$telco_match = ['name' => 'Icell'];
$telco = Telco::where($telco_match)->first();
try {
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' => $request->text,
'correlator' => $request->correlator,
'serviceid' => $request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
// Here you can pass it to the other method
this.subscribe($response, $telco); // <--- $response will be your "$request" parameter
$noti = new Notification_log();
$noti->error_message = (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}
Related
I am trying to make a post request to the example URL endpoint. When I make a post request in my localhost, it works fine, but when I try to request live serve with the same come, it returns null every time. So if I make a request that time, my end point gives a response, but it returns null when I make a post request.
public function saveEnquiry($request)
{
$ClientObj = new Client();
$url = 'endpoint_base_url/v1/business/enquiry';
$data = [
'name' => $request->name,
'lastname' => $request->lastname,
'email' => $request->email,
'mobile' => $request->mobile,
'country_code' => $request->country_code,
'from_page' => $request->from_page,
'message' => $request->message,
'package_slug' => $request->package_slug,
];
$body = ['debug', true, 'form_params' => $data];
try {
$response = $ClientObj->request('POST', $url, $body);
$res = json_decode($response->getBody()->getContents(), true);
if ($res['success'] == true && $res['data'] != null) {
/// logic part
} else {
throw new TripshifuException($res['message']);
}
} catch (BadResponseException $e) {
throw new TripshifuException(json_decode($e->getResponse()->getBody()->getContents()));
}
}
I am using backpack laravel. Though I am also using Backpack's own authentication, yet I need to maintain a different customer table for App usage. For the customer table, I am using JWTAuth for token generation, but token generation gets failed each time.
public function register(Request $request)
{
$checkEmail = Customer::where('email', $request->email)->first();
if ($checkEmail) {
$response = [
'email_already_used' => true,
];
return response()->json($response);
}
$payload = [
'password' => \Hash::make($request->password),
'email' => $request->email,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'auth_token' => '',
];
try {
$user = new \App\Models\Customer($payload);
if ($user->save()) {
$token = self::getToken($request->email, $request->password); // generate user token
if (!is_string($token)) {
return response()->json(['success' => false, 'data' => 'Token generation failed'], 201);
}
$user = \App\Models\Customer::where('email', $request->email)->get()->first();
$user->auth_token = $token; // update user token
$user->save();
$response = [
'success' => true,
'data' => [
'id' => $user->id,
'auth_token' => $token,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
],
];
} else {
$response = ['success' => false, 'data' => 'Couldnt register user'];
}
} catch (\Throwable $e) {
echo ($e);
$response = ['success' => false, 'data' => 'Couldnt register user.'];
return response()->json($response, 201);
}
return response()->json($response, 201);
}
I believe there might be some issue with guards.
Do I need to specify something in app/config.php for this?
when I wanna login with google account, I receive this error,
ClientException Client error: GET https://www.googleapis.com/plus/v1/people/me?prettyPrint=false
resulted in a 403 Forbidden response:
<meta name=viewport content="initial-scale=1,
minimum-scale=1, w (truncated...) in RequestException.php line 113
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
$social_user = Socialite::driver('google')->user();
$user = User::whereEmail($social_user->getEmail())->first();
if( ! $user ) {
$user = User::create([
'name' => $social_user->getName(),
'email' => $social_user->getEmail(),
'password' => bcrypt($social_user->getId())
]);
}
if($user->active == 0) {
$user->update([
'active' => 1
]);
}
auth()->loginUsingId($user->id);
return redirect('/');
}
From what i can see, you need to pass a token.
https://laravel.com/docs/master/socialite#retrieving-user-details
This is solution for this problem. I found it from this website.
https://github.com/laravel/socialite/pull/283/files
I Update GoogleProvider.php in my project. Comment sentences have to update.
GoogleProvider.php:
protected function getUserByToken($token)
{
// $response = $this->getHttpClient()->get('https://www.googleapis.com/plus/v1/people/me?', [
$response = $this->getHttpClient()->get('https://www.googleapis.com/userinfo/v2/me?', [
'query' => [
'prettyPrint' => 'false',
],
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$token,
],
]);
return json_decode($response->getBody(), true);
}
/**
* {#inheritdoc}
*/
protected function mapUserToObject(array $user)
{
return (new User)->setRaw($user)->map([
// 'id' => $user['id'], 'nickname' => array_get($user, 'nickname'), 'name' => $user['display Name'],
// 'email' => $user['emails'][0]['value'], 'avatar' => array_get($user, 'image')['url'],
'id' => $user['id'], 'nickname' => array_get($user, 'nickname'), 'name' => $user['name'],
'email' => $user['email'], 'avatar' => array_get($user, 'picture'),
]);
}
I want to send a request to external API using guzzle, but not foreach is not running.
public function recursub() {
$usersCheck = User::where('trialExpires', '<=', Carbon::now());
//Get all Check User
foreach ($usersCheck as $user) {
dd('Hello');
$url = 'https://api.##############';
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'#########################',
'Content-Type' => 'application/json'
],
'form_params' => [
'authorization_code' => $user->authorization_code,
'customer' => $user->email,
//'plan' => '#######################',
]
]);
It worked if I hardcode the value into the form paramas.
public function recursub() {
$usersCheck = User::where('trialExpires', '<=', Carbon::now())->get();
//Get all Check User
foreach ($usersCheck as $user) {
dd('Hello');
$url = 'https://api.##############';
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'#########################',
'Content-Type' => 'application/json'
],
'form_params' => [
'authorization_code' => $user->authorization_code,
'customer' => $user->email,
//'plan' => '#######################',
]
]);
get() method is used to get data in array, so now you have to add get() method in the last of the query. Here is the code below:
$usersCheck = User::where('trialExpires', '<=', Carbon::now())->get();
get() method is used for getting multiple records and first is used for single record.
I just noticed yesterday, there was a problem with my reCAPTCHA, last year was fine.
Here's my code:
public function message(Request $request) {
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LcwXi8UAAAAAE9zNCVfqwDOIWNazNgdK-0wQv9L',
'response' => $_POST["g-recaptcha-response"]
);
//For debug purpose (remove comments)
//dd($request->all());
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
return redirect('/')->with('success', 'You are a bot! Go away!');;
} else if ($captcha_success->success==true) {
$content = array (
'http' => array (
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
When I submitted contact form, it gave me this error:
ErrorException in PagesController.php line 37:
file_get_contents(): Content-type not specified assuming
application/x-www-form-urlencoded
Line 37 is:
$verify = file_get_contents($url, false, $context);
I've fixed this, here's my code:
private function check_recaptcha($key){
$secret = '6LdMgJIUAAAAAOvJPW8MHjumG2xQNNuRyw-WctqQ';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$key);
$responseData = json_decode($verifyResponse);
return ($responseData->success)? true:false;
}
public function message(Request $request) {
//Validate
$validator = Validator::make($request->all(), [
'name' => 'required',
'subject' => 'required',
'message' => 'required',
'email' => 'required|email',
'g-recaptcha-response' => 'required',
]);
//If validator failed
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
//Declare variable
$name = $request->input("name");
$email = $request->input("email");
$subject = $request->input("subject");
$message = $request->input("message");
$captchaKey = $request->input("g-recaptcha-response");
//Test reCAPTCHA
if (!$this->check_recaptcha($captchaKey)) {//captcha gagal
return redirect('/')->with('success', 'You are a bot! Go away!');
} else{//captcha sukses
$content = [
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message
];
In my case this header was missing and worked try this
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'Content-Type: application/x-www-form-urlencoded'
)
);