Paypal Express Checkout Error (Method Specified is not Supported) - php

I am new to codeigniter and paypal. I am working on gocart(an open source eCommerce solution built on codeIgniter). I try to work on paypal API integrated in it, but its showing error as follows :
[ACK] => Failure [L_ERRORCODE0] => 81002 [L_SHORTMESSAGE0] => Unspecified Method [L_LONGMESSAGE0] => Method Specified is not Supported [L_SEVERITYCODE0] => Error
Below is my code : paypal_expres.php
$this->RETURN_URL = 'www.example.com';
$this->CANCEL_URL = 'www.example.com';
$this->currency = 'USD';
$this->host = "api-3t.sandbox.paypal.com";
$this->gate = 'https://www.sandbox.paypal.com/cgi-bin/webscr?';
public function doExpressCheckout($amount, $desc, $invoice='') {
$data = array(
'PAYMENTACTION' =>'Sale',
'AMT' => '24',
'RETURNURL' => $this->getReturnTo(),
'CANCELURL' => $this->getReturnToCancel(),
'CURRENCYCODE'=> $this->currency,
'METHOD' => 'SetExpressCheckout'
);
$query = $this->buildQuery($data);
$result = $this->response($query);
$response = $result->getContent();
$return = $this->responseParse($response);
echo '';
print_r($return);
echo '';
if ($return['ACK'] == 'Success') {
header('Location: '.$this->gate.'cmd=_express-checkout&useraction=commit&token='.$return['TOKEN'].'');
}
return($return);
}
public function doExpressCheckout($amount, $desc, $invoice='') {
$data = array(
'PAYMENTACTION' =>'Sale',
'AMT' => '24',
'RETURNURL' => $this->getReturnTo(),
'CANCELURL' => $this->getReturnToCancel(),
'CURRENCYCODE'=> $this->currency,
'METHOD' => 'SetExpressCheckout'
);
$query = $this->buildQuery($data);
$result = $this->response($query);
$response = $result->getContent();
$return = $this->responseParse($response);
echo '';
print_r($return);
echo '';
if ($return['ACK'] == 'Success') {
header('Location: '.$this->gate.'cmd=_express-checkout&useraction=commit&token='.$return['TOKEN'].'');
die();
}
return($return);
}
private function response($data) {
$result = $this->CI->httprequest->connect($data);
if ($result<400) return $this->CI->httprequest;
return false;
}
private function buildQuery($data = array()) {
$data['USER'] = $this->API_USERNAME;
$data['PWD'] = $this->API_PASSWORD;
$data['SIGNATURE'] = $this->API_SIGNATURE;
$data['VERSION'] = '56.0';
$query = http_build_query($data);
return $query;
}

When Paypal returns this message it's a case of transmit method, not the method argument/property.
As in Paypal only accepts POST.

Related

laravel route findOrFail() problems

new with Laravel and I am trying to add a findOrFail on this specific route and it's giving me a hard time. What am I missing?
Route::get('/listing/{type}/{owner}/{id}/{address}', 'Properties\DisplayController#show');
Whats not working
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return Properties\DisplayController#show::findOrFail($id);
});
Error I am getting
Parse error: syntax error, unexpected '#', expecting ';'
controller/function I'm calling
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id);
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
Thanks for the help!
To return directly on route:
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return App\YourModel::findOrFail($id);
});
https://laravel.com/docs/5.3/eloquent#retrieving-single-models
Since the model is on another server that we connect to using GuzzleHTTP, I could not put findOfFail() on the model.
Here is the edit to the controller. Added in the ['http_errors' => false] which prevents guzzle from returning http errors, and then a if statement using getStatusCode() to find if it was a error 500 or not.
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id, ['http_errors' => false]);
if ($response->getStatusCode() == "500") {
abort(404);
}
else {
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
}

Phpunit test a method using a service

I'm trying to test a method which is using a service, and apparently it's not possible to test it like a normal method.
Does someone know what to do ?
I have this code for the moment :
namespace PlatformBundle\Tests;
use PlatformBundle\Controller\PaymentController;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class PaymentControllerTest extends WebTestCase
{
private $payment;
public function __construct() { parent::__construct(); $this->payment = new PaymentController(); }
public function testSendEmail()
{
$param = array(
'info' => array(
'email' => 'test#test.com', 'name' => 'test', 'fare' => 'test', 'id' => 'test'
)
);
$this->assertEquals(true, $this->invokeMethod($this->payment, 'sendEmail', $param));
}
/**
* Call protected/private method of a class.
*
* #param object &$object Instantiated object that we will run method on.
* #param string $methodName Method name to call
* #param array $parameters Array of parameters to pass into method.
*
* #return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
The controller where the method sendEmail is :
<?php
namespace PlatformBundle\Controller;
use PlatformBundle\Entity\Customer;
use PlatformBundle\Entity\Promocode;
use PlatformBundle\Entity\Transfer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class PaymentController extends Controller
{
public function checkoutAction(Request $req)
{
if (! $req->isMethod('POST')) throw new AccessDeniedHttpException();
$info = $req->request->all();
$this->container->get('platform.formSecurity')->testAllInformation($info);
$this->saveCustomerIntoDb($info);
$info['payed'] = false;
$session = $req->getSession();
$session->set('info', $info);
$info['date'] = $this->container->get('platform.useful')->reverseDateFormat($info['date']);
return $this->render('PlatformBundle:Payment:checkout.html.twig', array(
'isIndex' => false,
'info' => $info,
'stripe' => $this->stripeConfig()
));
}
public function cancelAction(Request $req)
{
$req->getSession()->invalidate();
return $this->render('PlatformBundle:Payment:cancel.html.twig', array('isIndex' => false));
}
public function successAction(Request $req)
{
$session = $req->getSession();
$info = $session->get('info');
if ($info['payed']) {
$req->getSession()->invalidate();
if ($info === null) throw new Exception('Please contact us to make sure that the payment has been done and that your order has been taken into account.');
$this->saveTransferIntoDb($info);
$customer = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')->findOneBy(array(
'email' => $info['email']
));
$transfer = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Transfer')->findOneBy(
array('customer' => $customer->getId()),
array('id' => 'desc'),
1
);
$info['id'] = $transfer->getId();
$info['date'] = $this->container->get('platform.useful')->reverseDateFormat($info['date']);
$this->sendEmail($info);
// if 5 payments done, send a promocode
if (is_int($customer->getPayments() / 5)) {
$this->createAndSendNewPromocode($customer);
}
return $this->render('PlatformBundle:Payment:success.html.twig', array(
'isIndex' => false,
'info' => $info
));
} else return new RedirectResponse('cancel');
}
private function sendEmail($info)
{
$mail = $this->container->get('platform.mail');
$mail->send(
$info['email'],
'You have ordered a transfer for Dublin',
$this->renderView('PlatformBundle:Mail:orderSucceed.html.twig', array('info' => $info)),
'info#dubair.ie'
);
$mail->send(
'info#airportcollections.net, info#dubair.ie, info#365onlineholidays.com',
'A customer ordered a transfer for Dublin',
$this->renderView('PlatformBundle:Mail:report.html.twig', array('info' => $info)),
'info#dubair.ie'
);
}
private function saveCustomerIntoDb($info)
{
// test if the customer already exist
$customersList = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')
->findByEmail($info['email']);
$customerExists = (sizeof($customersList) == 1 ? true : false);
if ($customerExists) {
$customer = $customersList[0];
} else {
// Create the entity
$customer = new Customer();
// dateRegistration, country and ip are automatically created in the constructor
$customer->setEmail($info['email']);
$customer->setPayments(0);
}
$customer->setName($info['name']);
$customer->setPhone($info['phone']);
$em = $this->getDoctrine()->getManager();
$em->persist($customer);
$em->flush();
}
private function saveTransferIntoDb($info)
{
$customers = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Customer')
->findByEmail($info['email']);
$customer = $customers[0];
$customer->setPayments($customer->getPayments() + 1);
// make promocode outdated
if ($info['promocode'] != '') {
$promocode = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Promocode')
->findOneBy(array(
'value' => $info['promocode'],
'outdated' => 0,
'type' => 'short'
));
$promocode->setOutdated(1);
}
// test if transfer already exist
$transferList = $this->getDoctrine()->getManager()->getRepository('PlatformBundle:Transfer')->findBy(
array(
'customer' => $customer,
'pickup' => $info['pickup'],
'destination' => $info['destination'],
'pickupTime' => $info['pickupTime'],
'address' => $info['address']
), // criteria
array('pickup' => 'desc'), // sorting
5, // Limit
0 // Offset
);
// if transfer doesn't already exist, create it
if (sizeof($transferList) == 0) {
$transfer = new Transfer();
$transfer->setPickup($info['pickup']);
$transfer->setDestination($info['destination']);
$dateArray = explode('-', $info['date']);
$transfer->setDate(new \DateTime($dateArray[2].'-'.$dateArray[1].'-'.$dateArray[0]));
$transfer->setAddress($info['address']);
$transfer->setFlightTime($info['flightTime']);
$transfer->setPickupTime($info['pickupTime']);
$transfer->setSeats($info['seats']);
$transfer->setAirline($info['airline']);
$transfer->setFlight($info['flight']);
$transfer->setType($info['type']);
$transfer->setBags($info['bags']);
$transfer->setFare($info['fare']);
// join
$transfer->setCustomer($customer);
$em = $this->getDoctrine()->getManager();
$em->persist($transfer);
$em->flush();
}
}
private function createAndSendNewPromocode($customer)
{
$newPromocode = $this->container->get('platform.useful')->createRandomPassword();
$promocode = new Promocode();
$promocode->setValue($newPromocode);
$promocode->setType('short');
$promocode->setDiscount(10);
$em = $this->getDoctrine()->getManager();
$em->persist($promocode);
$em->flush();
$mail = $this->container->get('platform.mail');
$mail->send(
$customer->getEmail(),
'A promotional code for your next transfer on dubair.ie !',
$this->renderView('PlatformBundle:Mail:promocode.html.twig', array(
'customer' => $customer,
'promocode' => $newPromocode
)),
'info#dubair.ie'
);
}
private function stripeConfig()
{
$stripe = array(
"secret_key" => "xx",
"publishable_key" => "xx"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
return $stripe;
}
public function stripeChargeAction(Request $req)
{
$this->stripeConfig();
$info = $req->getSession()->get('info');
$amount = ($info['fare'] * 100);
$info['payed'] = true;
$req->getSession()->set('info', $info);
$token = $req->request->get('stripeToken');
$customer = \Stripe\Customer::create(array(
'email' => $req->request->get('email'),
'card' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'eur'
));
return new RedirectResponse('success');
}
}
thanks

Add session for monitoring user after login using codeigniter

I tried to make the monitoring session but when adding script of the model script is not running?
Login controller:
public function do_login(){
$data = $this->input->post(null,true);
$result = $this->db->get_where('user',array('username'=>$data['username'],'password'=>md5(trim($data['password'])),))->row();
$is_login = $this->defaults->login($result); //load from model
if($is_login){
$session_set = array(
'is_login' => true,
'nama' => $is_login->nama,
'nik' => $is_login->nik,
'divisi' => $is_login->divisi,
'jabatan_id' => $is_login->jabatan_id,
'id_user' => $is_login->id_user,
'username' => $is_login->username,
'last_login' => $is_login->last_login
);
$this->db->update('user',array('last_login'=>date('Y-m-d H:i:s')),array('id_user'=>$is_login->id_user));
$this->session->set_userdata($session_set);
redirect('home/home');
} else {
redirect('login/login/index/error');
}
}
Model:
public function login() {
if ($this->agent->is_browser()) {
$agent =$this->agent->browser().''.$this->agent->version();
}
elseif ($this->agent->is_robot()) {
$agent = $this->agent->robot();
}
elseif ($this->agent->is_mobile()) {
$agent = $this->agent->mobile();
}
else {
$agent = 'Unidentified User Agent';
}
$username = $this->security->xss_clean($this->input->post('username'));
$data = array(
'namapengguna' => $username,
'platform' => $this->agent->platform(),
'browser' => $agent,
'logged_in' => true,);
$this->session->set_userdata($data);
return true;
}

bufferapp always returns me a NULL access_token

Here is the code:
$client_id = '';
$client_secret = '';
$callback_url = '';
$buffer = new BufferApp($client_id, $client_secret, $callback_url);
if (!$buffer->ok) {
echo 'Connect to Buffer!';
} else {
//this pulls all of the logged in user's profiles
$profiles = $buffer->go('/profiles');
if (is_array($profiles)) {
foreach ($profiles as $profile) {
//this creates a status on each one
$buffer->go('/updates/create', array('text' => 'My first status update from bufferapp-php worked!', 'profile_ids[]' => $profile->id));
}
}
}
if (isset($_GET['code']))
{
var_dump($_SESSION['oauth']['buffer']['access_token']);
}
it is an example code, I had to be returned the access_token, but it is NULL
trying to log in I'm redirected to the bufferapp' site, give the access, then I'm redirected back and it is NULL
what's the problem ?
thanks in advance)
the bufferapi code :
class BufferApp {
private $client_id;
private $client_secret;
private $code;
private $access_token;
private $callback_url;
private $authorize_url = 'https://bufferapp.com/oauth2/authorize';
private $access_token_url = 'https://api.bufferapp.com/1/oauth2/token.json';
private $buffer_url = 'https://api.bufferapp.com/1';
public $ok = false;
private $endpoints = array(
'/user' => 'get',
'/profiles' => 'get',
'/profiles/:id/schedules/update' => 'post', // Array schedules [0][days][]=mon, [0][times][]=12:00
'/profiles/:id/updates/reorder' => 'post', // Array order, int offset, bool utc
'/profiles/:id/updates/pending' => 'get',
'/profiles/:id/updates/sent' => 'get',
'/profiles/:id/schedules' => 'get',
'/profiles/:id' => 'get',
'/updates/:id/update' => 'post', // String text, Bool now, Array media ['link'], ['description'], ['picture'], Bool utc
'/updates/create' => 'post', // String text, Array profile_ids, Aool shorten, Bool now, Array media ['link'], ['description'], ['picture']
'/updates/:id/destroy' => 'post',
'/updates/:id' => 'get',
'/links/shares' => 'get',
);
public $errors = array(
'invalid-endpoint' => 'The endpoint you supplied does not appear to be valid.',
'403' => 'Permission denied.',
'404' => 'Endpoint not found.',
'405' => 'Method not allowed.',
'1000' => 'An unknown error occurred.',
'1001' => 'Access token required.',
'1002' => 'Not within application scope.',
'1003' => 'Parameter not recognized.',
'1004' => 'Required parameter missing.',
'1005' => 'Unsupported response format.',
'1010' => 'Profile could not be found.',
'1011' => 'No authorization to access profile.',
'1012' => 'Profile did not save successfully.',
'1013' => 'Profile schedule limit reached.',
'1014' => 'Profile limit for user has been reached.',
'1020' => 'Update could not be found.',
'1021' => 'No authorization to access update.',
'1022' => 'Update did not save successfully.',
'1023' => 'Update limit for profile has been reached.',
'1024' => 'Update limit for team profile has been reached.',
'1028' => 'Update soft limit for profile reached.',
'1030' => 'Media filetype not supported.',
'1031' => 'Media filesize out of acceptable range.',
);
public $responses = array(
'403' => 'Permission denied.',
'404' => 'Endpoint not found.',
'405' => 'Method not allowed.',
'500' => 'An unknown error occurred.',
'403' => 'Access token required.',
'403' => 'Not within application scope.',
'400' => 'Parameter not recognized.',
'400' => 'Required parameter missing.',
'406' => 'Unsupported response format.',
'404' => 'Profile could not be found.',
'403' => 'No authorization to access profile.',
'400' => 'Profile did not save successfully.',
'403' => 'Profile schedule limit reached.',
'403' => 'Profile limit for user has been reached.',
'404' => 'Update could not be found.',
'403' => 'No authorization to access update.',
'400' => 'Update did not save successfully.',
'403' => 'Update limit for profile has been reached.',
'403' => 'Update limit for team profile has been reached.',
'403' => 'Update soft limit for profile reached.',
'400' => 'Media filetype not supported.',
'400' => 'Media filesize out of acceptable range.',
);
function __construct($client_id = '', $client_secret = '', $callback_url = '') {
if ($client_id) $this->set_client_id($client_id);
if ($client_secret) $this->set_client_secret($client_secret);
if ($callback_url) $this->set_callback_url($callback_url);
if ($_GET['code']) {
$this->code = $_GET['code'];
$this->create_access_token_url();
}
$this->retrieve_access_token();
}
function go($endpoint = '', $data = '') {
if (in_array($endpoint, array_keys($this->endpoints))) {
$done_endpoint = $endpoint;
} else {
$ok = false;
foreach (array_keys($this->endpoints) as $done_endpoint) {
if (preg_match('/' . preg_replace('/(\:\w+)/i', '(\w+)', str_replace('/', '\/', $done_endpoint)) . '/i', $endpoint, $match)) {
$ok = true;
break;
}
}
if (!$ok) return $this->error('invalid-endpoint');
}
if (!$data || !is_array($data)) $data = array();
$data['access_token'] = $this->access_token;
$method = $this->endpoints[$done_endpoint]; //get() or post()
return $this->$method($this->buffer_url . $endpoint . '.json', $data);
}
function store_access_token() {
$_SESSION['oauth']['buffer']['access_token'] = $this->access_token;
}
function retrieve_access_token() {
$this->access_token = $_SESSION['oauth']['buffer']['access_token'];
if ($this->access_token) {
$this->ok = true;
}
}
function error($error) {
return (object) array('error' => $this->errors[$error]);
}
function create_access_token_url() {
$data = array(
'code' => $this->code,
'grant_type' => 'authorization_code',
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->callback_url,
);
$obj = $this->post($this->access_token_url, $data);
$this->access_token = $obj->access_token;
$this->store_access_token();
}
function req($url = '', $data = '', $post = true) {
if (!$url) return false;
if (!$data || !is_array($data)) $data = array();
$options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false);
if ($post) {
$options += array(
CURLOPT_POST => $post,
CURLOPT_POSTFIELDS => $data
);
} else {
$url .= '?' . http_build_query($data);
}
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$rs = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code >= 400) {
return $this->error($code);
}
return json_decode($rs);
}
function get($url = '', $data = '') {
return $this->req($url, $data, false);
}
function post($url = '', $data = '') {
return $this->req($url, $data, true);
}
function get_login_url() {
return $this->authorize_url . '?'
. 'client_id=' . $this->client_id
. '&redirect_uri=' . urlencode($this->callback_url)
. '&response_type=code';
}
function set_client_id($client_id) {
$this->client_id = $client_id;
}
function set_client_secret($client_secret) {
$this->client_secret = $client_secret;
}
function set_callback_url($callback_url) {
$this->callback_url = $callback_url;
}
}

LinkedIn API Request Failed HTTP 400

I am having problems with the LinkedIn API, sometimes it's working fine and sometimes I just get the following error:
Message:
file_get_contents(https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&client_id=####&client_secret=####&code=AQTJH8Hm9K8gmriHaDPLbJm_-E8OnbsiUCZvz32Jv_wD6idTW7Se8v0dohVUH0m8zGWzfKkanCC_NT3smdkoykE0nF88nH-tntK35UqHH4LwgzfcNBc&redirect_uri=http%3A%2F%2Fpeerbriefmini.local%2Flinkedincontroller)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.0 400 request#no_content_length
I have taken out my app id and secret. Is there are reason why it would sometimes work?
Edit : added the php code, which works in codeigniter
<?php
class Linkedincontroller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->config->load('linkedin');
$this->load->library('linkedin');
$this->load->model('account_model');
}
public function index() {
// Change these
define('API_KEY', '###');
define('API_SECRET', '##');
define('REDIRECT_URI', base_url().'linkedincontroller');
define('SCOPE', 'r_fullprofile r_emailaddress rw_nus r_basicprofile r_contactinfo');
// You'll probably use a database
session_name('dfsfsdfsdf');
session_start();
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
$this->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
//exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
$this->getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = $this->fetch('GET', '/v1/people/~:(id,first-name,last-name,main-address,picture-url,public-profile-url,email-address,interests,skills,languages,certifications,educations,positions,courses)');
$linkedin_id = $user['id'];
if(isset($linkedin_id)) {
//var_dump($user);
$linkedin_id = $user['id'];
$linkedin_url = $user['publicProfileUrl'];
$first_name = $user['firstName'];
$last_name = $user['lastName'];
$email = $user['emailAddress'];
$profile_picture = $user['pictureUrl'];
$address = $user['mainAddress'];
$this->account_model->insert_database('accounts',
array(
'account_confirmed' => 1,
'account_active' => 1,
'account_level' => 'Parent',
'account_role' => 'User',
'account_type' => 'Referrer',
'account_completed_level' => 1,
'master_account' => 1,
'account_holder' => $first_name . ' ' .$last_name,
'email' => $email,
'linkedin_id' => $linkedin_id
)
);
$account_id = $this->db->insert_id();
$this->account_model->insert_database('profiles',
array(
'account_id' => $account_id,
'profile_picture' => $profile_picture,
'linkedin_url' => $linkedin_url,
'address' => $address
)
);
// set flash data
$this->session->set_userdata(
array('linkedin_id' => $linkedin_id,
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'profile_picture' => $profile_picture,
'residential_address' => $address)
);
// redirect back to reg page with profile data
redirect('register');
}else{
$data['header_text'] = $this->account_model->header_text();
$data['header_links'] = $this->account_model->header_links();
$data['user_picture'] = '';
$data['nickname'] = $this->account_model->user_nickname();
$this->load->view('template/header', $data);
$data['error_message'] = 'Unknown LinkedIn credentials.';
$this->load->view('error', $data);
$this->load->view('template/footer');
}
}
// empty fields
private function empty_fields($value) {
if(isset($value)) {
return $value;
}else{
return NULL;
}
}
// authorization code
private function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
}
// get access token
private function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
// fetch
private function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response, true);
//return json_decode($response, false);
}
}
?>

Categories