call a function in different namespacs php - php

I learn MVC recently. I try to rebulid my website in MVC structure, and i have a problem to call function inside different name sapace(maybe i don't know about OOP very much). Here is my code:
namespace UserFrosting;
class GroupController extends \UserFrosting\BaseController {
public function testFunction($params){
//Simple test function that i had error: Call to undefined function UserFrosting\testFunction()
$params['Password'] = $pw;
$params['JSON'] = 'Yes';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
if (curl_errno($curl)) $obj = (object) array('Result' => 'Error', 'Error' => curl_error($curl));
else if (empty($response)) $obj = (object) array('Result' => 'Error', 'Error' => 'Connection failed');
else $obj = json_decode($response);
curl_close($curl);
return $obj;
}
public function loginNumber(){
$params = array("Command" => "SystemStats");
$api = testFunction($params);
echo "<h3>Server Status</h3>\r\n";
if ($api -> Result == "Error") die("Error: " . $api -> Error);
echo "Logins: " . $api -> Logins . "<br/>\r\n";
}
}
So basically i called loginNumber(), then it shows this error:*
Call to undefined function UserFrosting\testFunction()*
I had same problem with SoupClient but i shows this error:*
Class 'UserFrosting\SoapClient' not found*
here is my soapClient code in same namesapce:
public function templatePost(){
$client = SoapClient('https://www.test.com/pg/services/WebGate/wsdl', ['encoding' => 'UTF-8']);
$result = $client->PaymentRequest([
'MerchantID' => $MerchantID,
'Amount' => $Amount,
'Description' => $Description,
'Email' => $Email,
'Mobile' => $Mobile,
'CallbackURL' => $CallbackURL,
]);
if ($result->Status == 100) {
header('Location: https://www.test.com/pg/StartPay/'.$result->Authority);
} else {
echo'ERR: '.$result->Status;
}
}
I had the same error, what is my problem? how can i call these functions?

Explanation: You do not have a function testFunction, but the object GroupController has a method testFuntion. So you need to use $this->.. since you are already inside that class. Your loginNumber should read:
public function loginNumber(){
$params = array("Command" => "SystemStats");
$api = $this->testFunction($params);
echo "<h3>Server Status</h3>\r\n";
if ($api -> Result == "Error") die("Error: " . $api -> Error);
echo "Logins: " . $api -> Logins . "<br/>\r\n";
}
In your second question you are not importing the class SoapClient correctly. Please try:
$client = \SoapClient(...);
This uses SoapClient from root namespace.

Related

database is not updating the values after successful transaction through payment gateway

My website's framework is in CodeIgniter. I have integrated instamojo payment gateway in it. The query inserting the payment id but after successful payment not updating the column value of status to 1 from 0,
This is the block code of paymentcontroller.php
public static function userDataUpdate($trx)
{
$general = getGeneral();
$data = Deposit::where('trx', $trx)->first();
if ($data->status == 0) {
$data->status = 1;
$data->save();
$user = User::find($data->user_id);
$wallet = $user->wallet;
$wallet->balance += $data->amount;
$wallet->save();
$transaction = new Transaction();
$transaction->user_id = $data->user_id;
$transaction->amount = $data->amount;
$transaction->post_balance = $wallet->balance;
$transaction->charge = $data->charge;
$transaction->trx_type = '+';
$transaction->details = 'Deposited via ' . $data->gatewayCurrency()->name;
$transaction->trx = $data->trx;
$transaction->save();
$adminNotification = new AdminNotification();
$adminNotification->user_id = $user->id;
$adminNotification->title = 'Deposit succeeded via '.$data->gatewayCurrency()->name;
$adminNotification->click_url = urlPath('admin.deposit.successful');
$adminNotification->save();
notify($user, 'DEPOSIT_COMPLETE', [
'method_name' => $data->gatewayCurrency()->name,
'method_currency' => $data->method_currency,
'method_amount' => showAmount($data->final_amo),
'amount' => showAmount($data->amount),
'charge' => showAmount($data->charge),
'currency' => $general->cur_text,
'rate' => showAmount($data->rate),
'trx' => $data->trx,
'post_balance' => showAmount($wallet->balance)
]);
}
}
This is the code of processcontroller.php
<?php
namespace App\Http\Controllers\Gateway\Instamojo;
use App\Models\Deposit;
use App\Http\Controllers\Gateway\PaymentController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProcessController extends Controller
{
/*
* Instamojo Gateway
*/
public static function process($deposit)
{
$basic = getGeneral();
$instaMojoAcc = json_decode($deposit->gatewayCurrency()->gateway_parameter);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://test.instamojo.com/api/1.1/payment-requests/');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
"X-Api-Key:$instaMojoAcc->api_key",
"X-Auth-Token:$instaMojoAcc->auth_token"
)
);
$payload = array(
'purpose' => 'Payment to ' . $basic->sitename,
'amount' => round($deposit->final_amo,2),
'buyer_name' => $deposit->user->username,
'redirect_url' => route('user.deposit.history'),
'webhook' => route('ipn.'.$deposit->gateway->alias),
'email' => $deposit->user->email,
'btc_wallet' => $deposit->trx,
'send_email' => true,
'allow_repeated_payments' => false
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
curl_close($ch);
$res = json_decode($response);
if (#$res->success) {
if(!#$res->payment_request->id){
$send['error'] = true;
$send['message'] = "Response not given from API. Please re-check the API credentials.";
}else{
$deposit->btc_wallet = $res->payment_request->id;
$deposit->save();
$send['redirect'] = true;
$send['redirect_url'] = $res->payment_request->longurl;
$send['btc_wallet'] = $deposit->trx;
}
} else {
$send['error'] = true;
$send['message'] = "Credentials mismatch. Please contact with admin";
}
return json_encode($send);
}
public function ipn(Request $request)
{
//$this->customLog($request->all(),'Instamojo',true);
$deposit = Deposit::where('btc_wallet', $_POST['payment_request_id'])->orderBy('id', 'DESC')->first();
$instaMojoAcc = json_decode($deposit->gatewayCurrency()->gateway_parameter);
$deposit->detail = $request->all();
$deposit->save();
$imData = $_POST;
$macSent = $imData['mac'];
unset($imData['mac']);
ksort($imData, SORT_STRING | SORT_FLAG_CASE);
$mac = hash_hmac("sha1", implode("|", $imData), $instaMojoAcc->salt);
if ($macSent == $mac && $imData['status'] == "Credit" && $deposit->status == '0') {
PaymentController::userDataUpdate($deposit->trx);
}
}
}
I am unable to find out why the query is not updating the status of the transaction in mysqli.

WordPress - Issues with referencing custom PHP class in functions.php

I apologize if this is really dumb/obvious but this is my first experience working with classes in WordPress.
I made a class called SharpSpringService.php inside my custom plugin sharpspring-form. I placed the class within a classes folder within that custom plugin for organization purposes.
I'm referencing the SharpSpringService class within a function in functions.php but am getting an error. When I declare a new instance of SharpSpringService and place the account ID and secret key as parameters, I get a message: "Expected SharpSpring, got string". I also see an Internal Server 500 Error in the Chrome dev consoles that seems to be a result of creating an instance of this class.
I'm not sure why the parameters are expected to be "SharpSpring" as they should be accountID and secretkey.
Here is the SharpSpringService class:
private $authError = false;
private $accountID = null;
private $secretKey = null;
/**
* SharpSpringService constructor.
* #param $accountID SharpSpring Account ID
* #param $secretKey SharpSpring Secret Key
*/
public function __construct($accountID, $secretKey)
{
$this->accountID = $accountID;
$this->secretKey = $secretKey;
}
public function hasAuthError() {
return $this->authError;
}
public function makeCall($method, $params = []) {
$requestID = session_id();
$accountID = $this->accountID;
$secretKey = $this->secretKey;
$data = array(
'method' => $method,
'params' => $params,
'id' => $requestID,
);
$queryString = http_build_query([
'accountID' => $accountID,
'secretKey' => $secretKey
]);
$url = "http://api.sharpspring.com/pubapi/v1/?$queryString";
$data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
));
$result = curl_exec($ch);
curl_close($ch);
$resultObj = json_decode($result);
if ($resultObj->error != null) {
throw new \Exception($result->error);
}
return $resultObj;
}
}
And here is the function in functions.php that is referencing the class:
function get_memberships_callback(){
$newsListID = 550280195;
$listName = "NewsList";
$contactEmail = $_POST['contactemail'];
$sharpSpringService = new SharpSpringService('[redacted]', '[redacted]'); //this is where the code chokes
$return = [];
if($contactEmail != null && $contactEmail !=""){
$lists = $sharpSpringService->makeCall('getListMemberships', [
'emailAddress' => $contactEmail,
]);
if (count($lists) > 0) {
$listArray = json_decode(json_encode($lists), true);
$inNewsList = false;
foreach($listArray as $list){
if($list = $newsListID){
//the user is subscribed to the news list
$inNewsList = true;
$converted_result = ($inNewsList) ? 'true' : 'false';
}
}
}
$return[] = array(
"status" => $converted_result,
"list" => $listName
);
return json_encode($return);
}
else{
return $return;
}
die();
}
For calling numerous files, it is sometimes convenient to define a constant:
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'includes/admin-page.php');
include( MY_PLUGIN_PATH . 'includes/classes.php');

Implement Payum/Laravel recurring payment

I have some issues trying to get this working, I've implemented the checkout express (or seems to be) successfully, but also my system needs subscription option, following this example.
Now, my problem is that in Laravel you cannot simply put some random files, so I'm trying to do it in the correct way, sadly, there is no documentation of the classes and methods including on the library.
I've created some functions within controllers (I don't know if this the right way) the problem I'm facing now is trying to createRecurringPayment() to apply the desired amount of the recurring payment, is the final step I guess.
Thanks for yout help.
app/controllers/PaypalController.php
public function prepareExpressCheckout(){
$storage = $this->getPayum()->getStorage('Payum\Core\Model\ArrayObject');
$details = $storage->createModel();
$details['PAYMENTREQUEST_0_CURRENCYCODE'] = 'USD';
$details['PAYMENTREQUEST_0_AMT'] = 1.23;
$storage->updateModel($details);
$captureToken = $this->getTokenFactory()->createCaptureToken('paypal_es', $details, 'payment_done');
$details['RETURNURL'] = $captureToken->getTargetUrl();
$details['CANCELURL'] = $captureToken->getTargetUrl();
$storage->updateModel($details);
return \Redirect::to($captureToken->getTargetUrl());
}
public function prepareSubscribe(){
$storage = $this->getPayum()->getStorage('Payum\Core\Model\ArrayObject');
$details = $storage->createModel();
$details['PAYMENTREQUEST_0_AMT'] = 0;
$details['L_BILLINGTYPE0'] = Api::BILLINGTYPE_RECURRING_PAYMENTS;
$details['L_BILLINGAGREEMENTDESCRIPTION0'] = "SuscripciĆ³n por X meses";
$details['NOSHIPPING'] = 1;
$storage->updateModel($details);
$captureToken = $this->getTokenFactory()->createCaptureToken('paypal_es', $details, 'payment_done');
$storage->updateModel($details);
return \Redirect::to($captureToken->getTargetUrl());
}
public function createRecurringPayment(){
$payum_token = Input::get('payum_token');
$request = \App::make('request');
$request->attributes->set('payum_token', $payum_token);
$token = ($request);
//$this->invalidate($token);
$agreementStatus = new GetHumanStatus($token);
$payment->execute($agreementStatus);
if (!$agreementStatus->isSuccess()) {
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
$agreementDetails = $agreementStatus->getModel();
$storage = $this->getPayum()->getStorage('Payum\Core\Model\ArrayObject');
$recurringPaymentDetails = $storage->createModel();
$recurringPaymentDetails['TOKEN'] = $agreementDetails['TOKEN'];
$recurringPaymentDetails['DESC'] = 'Subscribe to weather forecast for a week. It is 0.05$ per day.';
$recurringPaymentDetails['EMAIL'] = $agreementDetails['EMAIL'];
$recurringPaymentDetails['AMT'] = 0.05;
$recurringPaymentDetails['CURRENCYCODE'] = 'USD';
$recurringPaymentDetails['BILLINGFREQUENCY'] = 7;
$recurringPaymentDetails['PROFILESTARTDATE'] = date(DATE_ATOM);
$recurringPaymentDetails['BILLINGPERIOD'] = Api::BILLINGPERIOD_DAY;
$payment->execute(new CreateRecurringPaymentProfile($recurringPaymentDetails));
$payment->execute(new Sync($recurringPaymentDetails));
$doneToken = $this->createToken('paypal_es', $recurringPaymentDetails, 'payment_done');
return \Redirect::to($doneToken->getTargetUrl());
}
app/routes.php
Route::get('/payment', array('as' => 'payment', 'uses' => 'PaymentController#payment'));
Route::get('/payment/done', array('as' => 'payment_done', 'uses' => 'PaymentController#done'));
Route::get('/payment/paypal/express-checkout/prepare', array('as' => 'paypal_es_prepare', 'uses' => 'PaypalController#prepareExpressCheckout'));
Route::get('/payment/paypal/subscribe/prepare', array('as' => 'paypal_re_prepare', 'uses' => 'PaypalController#prepareSubscribe'));
Route::get('/payment/paypal/subscribe/create', array('as' => 'payment_create', 'uses' => 'PaypalController#createRecurringPayment'));
I have found the problem. It is with the parameters we pass to the create recurring payment function. Here are functions for agreement and payment creation. It should work fine.
<?php
namespace App\Http\Controllers;
use Payum\Core\Request\GetHumanStatus;
use Payum\LaravelPackage\Controller\PayumController;
use Payum\Paypal\ExpressCheckout\Nvp\Api;
use Payum\Core\Request\Sync;
use Payum\Paypal\ExpressCheckout\Nvp\Request\Api\CreateRecurringPaymentProfile;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PayPalController extends PayumController {
public function prepareSubscribeAgreement() {
$storage = $this->getPayum()->getStorage('Payum\Core\Model\ArrayObject');
$details = $storage->create();
$details['PAYMENTREQUEST_0_AMT'] = 0;
$details['L_BILLINGTYPE0'] = Api::BILLINGTYPE_RECURRING_PAYMENTS;
$details['L_BILLINGAGREEMENTDESCRIPTION0'] = "Weather subscription";
//$details['NOSHIPPING'] = 1;
$storage->update($details);
$captureToken = $this->getPayum()->getTokenFactory()->createCaptureToken('paypal_ec', $details, 'paypal_subscribe');
return \Redirect::to($captureToken->getTargetUrl());
}
public function createSubscribePayment(Request $request) {
$request->attributes->set('payum_token', $request->input('payum_token'));
$token = $this->getPayum()->getHttpRequestVerifier()->verify($request);
$gateway = $this->getPayum()->getGateway($token->getGatewayName());
$agreementStatus = new GetHumanStatus($token);
$gateway->execute($agreementStatus);
if (!$agreementStatus->isCaptured()) {
header('HTTP/1.1 400 Bad Request', true, 400);
exit;
}
$agreement = $agreementStatus->getModel();
$storage = $this->getPayum()->getStorage('Payum\Core\Model\ArrayObject');
$recurringPayment = $storage->create();
$recurringPayment['TOKEN'] = $agreement['TOKEN'];
$recurringPayment['PAYERID'] = $agreement['PAYERID'];
$recurringPayment['PROFILESTARTDATE'] = date(DATE_ATOM);
$recurringPayment['DESC'] = $agreement['L_BILLINGAGREEMENTDESCRIPTION0'];
$recurringPayment['BILLINGPERIOD'] = Api::BILLINGPERIOD_DAY;
$recurringPayment['BILLINGFREQUENCY'] = 7;
$recurringPayment['AMT'] = 0.05;
$recurringPayment['CURRENCYCODE'] = 'USD';
$recurringPayment['COUNTRYCODE'] = 'US';
$recurringPayment['MAXFAILEDPAYMENTS'] = 3;
$gateway->execute(new CreateRecurringPaymentProfile($recurringPayment));
$gateway->execute(new Sync($recurringPayment));
$captureToken = $this->getPayum()->getTokenFactory()->createCaptureToken('paypal_ec', $recurringPayment, 'payment_done');
return \Redirect::to($captureToken->getTargetUrl());
}
public function done(Request $request) {
/** #var Request $request */
//$request = \App::make('request');
$request->attributes->set('payum_token', $request->input('payum_token'));
$token = $this->getPayum()->getHttpRequestVerifier()->verify($request);
$gateway = $this->getPayum()->getGateway($token->getGatewayName());
$gateway->execute($status = new GetHumanStatus($token));
return \Response::json(array(
'status' => $status->getValue(),
'details' => iterator_to_array($status->getFirstModel())
));
}
}
The routes:
Route::get('paypal/agreement', 'PayPalController#prepareSubscribeAgreement');
Route::get('paypal/subscribe', [
'as' => 'paypal_subscribe',
'uses' => 'PayPalController#createSubscribePayment'
]);
Route::get('paydone', [
'as' => 'payment_done',
'uses' => 'PayPalController#done'
]);
Simply open www.example.com/paypal/agreement and it should take you to PayPal
In my project I used the following library and it helped me alot:
https://github.com/amirduran/duranius-paypal-rest-api-php-library
Here are some features:
Easy to install - Just one file
Library is implemented as PHP class
It supports Recurring Payments It supports ExpressCheckout payments
All available PayPal API methods are wrapped in belonging methods
Well documented
Here is my Pay Pal REST API code.
//Request Perms
$cardtype = $request->cardtype;
$account_number = $request->cardnumber;
$expire_date =$request->expire_date;
$cvv = $request->cvv;
$plan_id =$request->plan_id;
$amount = $request->amount;
$userid = $request->user_id;
$payment_type = $request->plan_type;
//Genrate tokens
$ch = curl_init();
$clientId ='Your Client ID';
$clientSecret= 'Your Secret ID';
//you get Clientid and clientSecret
https://developer.paypal.com/developer/applications
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$clientSecret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$result = curl_exec($ch);
if(empty($result))die("Error: No response.");
else
{
$json = json_decode($result);
}
curl_close($ch);
$product_id = '';
//you can create payment plan this link
https://www.sandbox.paypal.com/billing/plans
if ($plan_id == 1) {
$product_id = 'your plan id';
}elseif ($plan_id == 2) {
$product_id = 'your plan id';
}
$ch = curl_init();
$payment_data = '{
"plan_id":"'.$product_id.'",
"start_time":"'.gmdate("Y-m-d\TH:i:s\Z",strtotime("+1 day")).'",
"shipping_amount":{
"currency_code":"USD",
"value":"'.$amount.'"
},
"subscriber":{
"name":{
"given_name":"",
"surname":""
},
"email_address":"'.$users->email.'",
"shipping_address":{
"name":{
"full_name":""
},
"address":{
"address_line_1":"",
"address_line_2":"",
"admin_area_2":"",
"admin_area_1":"",
"postal_code":"",
"country_code":"US"
}
},
"payment_source":{
"card":{
"number":"'.$account_number.'",
"expiry":"'. $expiry_date.'",
"security_code":"'.$cvv.'",
"name":"",
"billing_address":{
"address_line_1":"",
"address_line_2":"",
"admin_area_1":"",
"admin_area_2":"",
"postal_code":"",
"country_code":"US"
}
}
}
}
}';
curl_setopt($ch, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/billing/subscriptions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payment_data);
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Authorization: Bearer '.$json->access_token.'';
$headers[] = 'Paypal-Request-Id: SUBSCRIPTION-'. rand() .'';
$headers[] = 'Prefer: return=representation';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$payment_id = json_decode($result);
$data =$headers[2];
$subid = substr($data, strpos($data, ":") + 2);
//save data in database
$payment = new Subscription();
$payment->userid=$userid;
$payment->plan_id=$plan_id;
$payment->price=$amount;
$payment->sub_id=$subid;
$payment->transaction_id=$payment_id->id;
$payment->payment_type='Paypal';
$payment->charge=$paypal_charge;
$payment->plan_type=$plan_type;
$payment->subscription_startdate= $subscription_startdate;
$payment->subscription_enddate= $subscription_enddate;
$payment->subscription_status= 'active';
$payment->save();
return response()->json(['status' => true,'message'=>'Payment has been successfully Done','data'=>$payment]);
It's working fine for me.

How to get Citrix's Goto Meeting Access Token

Hi i am trying to get Goto meeting OAuth access token via php curl. but it returns nothing when i make a call. please guide me how i can get it, Code is given below.
$api_key = "123456";
$redirect_url = urlencode("URL");
$webinar_url = "https://api.citrixonline.com/oauth/authorize?client_id=".$api_key."&redirect_uri=".$redirect_url;
function getWebinarData($link)
{
$headers = array(
"HTTP/1.1",
"Content-type: application/json",
"Accept: application/json"
);
$curl = curl_init($link);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //2
$response = curl_exec($curl);
echo "<pre>DATA: ";print_r($response);echo "</pre>";
curl_close($curl);
return $response;
}
/**
* goto api
* Author: Ahad Ali
* Date: valentines day 2013
* Classes Curl, OAuth, GotoTraining
*/
define ("API_KEY", "");
define ("REDIRECT_URL","");
define ("AUTH_AUTOLOGIN_URL","https://developer.citrixonline.com/oauth/g2t/authorize.php");
define ("AUTH_EXCHANGE_URL", "https://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code=<CODE>&client_id=" . API_KEY);
define ("MANAGE_TRAINING_URL","https://api.citrixonline.com/G2T/rest/organizers/<ORGANIZERKEY>/trainings");
class Curl
{
public $result;
public function __construct()
{
}
public function request($url, $data="", $method="get", $headers="")
{
$ch = curl_init();
// this is autologiM USING CURL POST
// avoiding the redirect to gotos site where it asks for email and password and redirects back to the URL with a code
curl_setopt($ch, CURLOPT_URL, $url);
if($method == "post")
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, true);
}
if($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->result = (string) curl_exec($ch);
curl_close($ch);
return $this->result;
}
public function __destruct()
{
}
}
class OAuth
{
public $autologin_url;
public $exchange_url;
public $code;
public $auth_result;
//https://api.citrixonline.com/oauth/authorize?client_id= used this URL to get all the field names
public $login_data = array(
'emailAddress' => '',
'password' => '',
'client_id' => '',
'access_type'=> 'G2T',
'app_name' => '',
'redirect_uri' => '',
'submitted' => 'form_submitted',
);
public function __construct($autologin_url = AUTH_AUTOLOGIN_URL, $exchange_url = AUTH_EXCHANGE_URL, $apikey=API_KEY)
{
$this->autologin_url = $autologin_url;
$this->exchange_url = $exchange_url;
$this->login_data['client_id'] = $apikey;
}
public function authorize()
{
$this->getCode();
$this->exchangeCodeForAccessToken();
}
public function getCode()
{
$curl = new Curl();
$result = $curl->request($this->autologin_url, $this->login_data, "post");
$arr = explode("\n", $result);
foreach($arr as $k=>$v)
{
if(strstr($v,"Location: http:"))
$return_url = $v;
}
$query = trim(parse_url($return_url, PHP_URL_QUERY));// adds one unnecessary _ (underscore) at the end of the query string
$this->code = substr($query, 5, (strlen($query) - 6));//starting from 5 get me ...number of chars
}
function exchangeCodeForAccessToken()
{
$this->exchange_url = str_replace("<CODE>", $this->code, $this->exchange_url);
$curl = new Curl();
$result = $curl->request($this->exchange_url);
$this->auth_result = json_decode($result);
}
public function __destruct()
{
}
}
class GotoTraining extends OAuth
{
public $manage_training_url;
public $training_result;
public $error_list = array("AuthFailure", "AccessDenied", "ExpiredToken", "InternalError", "InvalidRequest", "InvalidMethod", "MissingToken", "NoSuchTraining", "InvalidToken");
public function __construct($url = MANAGE_TRAINING_URL)
{
$this->manage_training_url = $url;
parent::__construct();
}
/**
*Arguement List for goto CreateTraining service
* [name] => Representational State Transfer 101
[description] => The REST-ful way to APIs.
[timeZone] => America/Los_Angeles
[times] => Array
(
[0] => stdClass Object
(
[startDate] => 2011-09-08T18:25:00Z
[endDate] => 2011-09-08T19:25:00Z
)
[1] => stdClass Object
(
[startDate] => 2011-09-09T18:25:00Z
[endDate] => 2011-09-09T19:25:00Z
)
)
[registrationSettings] => stdClass Object
(
[disableWebRegistration] => false
[disableConfirmationEmail] => false
)
[organizers] => Array
(
[0] => 6512477
[1] => 38712
[2] => 9876466
)
*/
public function createTraining($name, $desc, $times)
{
$registrationSettings["disableWebRegistration"] = "false";
$registrationSettings["disableConfirmationEmail"] = "false";
$json["name"] = $name;
$json["description"] = $desc;
$json["timeZone"] = "Australia/Sydney";
$json["times"] = $times;//array for startDate, endDate
$json["registrationSettings"] = $registrationSettings;
$json["organizers"][0] = $this->auth_result->organizer_key;
$this->manage_training_url = str_replace("<ORGANIZERKEY>", $this->auth_result->organizer_key, $this->manage_training_url);
$json = json_encode($json);
//$post_data[] = "Authorization:OAuth oauth_token=" . $this->auth_result->access_token;
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token=' . $this->auth_result->access_token
);
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$curl = new Curl();
$this->training_result = $curl->request($this->manage_training_url, $json, "post", $headers);
$arr = explode("\n", $this->training_result);
$this->webCode = trim($arr[count($arr)-1], '"');
$this->checkError();
return $this->webCode;
}
public function checkError()
{
foreach($this->error_list as $val)
{
if(strstr($this->training_result, $val))
$this->webCode = $val;
}
return 0;
}
}

Call to undefined function that isn't undefined?

So, when I try and run this line of code, I'm getting the following error:
Fatal error: Call to undefined function curl_http_api_request_() in /Applications/XAMPP/xamppfiles/htdocs/CI/application/libraries/Shopify.php on line 58
Where line 58 is specifically this line:
$response = curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
I'm not really sure why it can't call the second function. The code is below. I've got no clue and am at a loss as to what the issue is.
class Shopify
{
public $_api_key;
public $_shared_secret;
public $CI; // To hold the CI superglobal
public function __construct ()
{
$this->_assign_libraries(); // Loads the CI superglobal and loads the config into it
// Get values from the CI config
$this->_api_key = $this->CI->config->item('api_key', 'shopify');
$this->_shared_secret = $this->CI->config->item('shared_secret', 'shopify');
}
public function shopify_app_install_url($shop_domain)
{
return "http://$shop_domain/admin/api/auth?api_key=". $this->_api_key;
}
public function shopify_is_app_installed($shop, $t, $timestamp, $signature)
{
return (md5($this->_shared_secret . "shop={$shop}t={$t}timestamp={$timestamp}") === $signature);
}
public function shopify_api_client($shops_myshopify_domain, $shops_token, $private_app=false)
{
$password = $private_app ? $this->_shared_secret : md5($this->_shared_secret.$shops_token);
$baseurl = "https://" . $this->_api_key . ":$password#$shops_myshopify_domain/";
return function ($method, $path, $params=array(), &$response_headers=array()) use ($baseurl)
{
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
$response = curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
$response = json_decode($response, true);
if (isset($response['errors']) or ($response_headers['http_status_code'] >= 400))
throw new ShopifyApiException(compact('method', 'path', 'params', 'response_headers', 'response', 'shops_myshopify_domain', 'shops_token'));
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
};
}
public function curl_http_api_request_($method, $url, $query='', $payload='', $request_headers=array(), &$response_headers=array())
{
$url = curl_append_query_($url, $query);
$ch = curl_init($url);
curl_setopts_($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response_headers = $this->curl_parse_headers_($message_headers);
return $message_body;
}
private function curl_append_query_($url, $query)
{
if (empty($query)) return $url;
if (is_array($query)) return "$url?".http_build_query($query);
else return "$url?$query";
}
private function curl_setopts_($ch, $method, $payload, $request_headers)
{
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, 'HAC');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if ('GET' == $method)
{
curl_setopt($ch, CURLOPT_HTTPGET, true);
}
else
{
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($request_headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
if (!empty($payload))
{
if (is_array($payload)) $payload = http_build_query($payload);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
}
}
}
private function curl_parse_headers_($message_headers)
{
$header_lines = preg_split("/\r\n|\n|\r/", $message_headers);
$headers = array();
list(, $headers['http_status_code'], $headers['http_status_message']) = explode(' ', trim(array_shift($header_lines)), 3);
foreach ($header_lines as $header_line)
{
list($name, $value) = explode(':', $header_line, 2);
$name = strtolower($name);
$headers[$name] = trim($value);
}
return $headers;
}
public function shopify_calls_made($response_headers)
{
return shopify_shop_api_call_limit_param_(0, $response_headers);
}
public function shopify_call_limit($response_headers)
{
return shopify_shop_api_call_limit_param_(1, $response_headers);
}
public function shopify_calls_left($response_headers)
{
return shopify_call_limit($response_headers) - shopify_calls_made($response_headers);
}
private function shopify_shop_api_call_limit_param_($index, $response_headers)
{
$params = explode('/', $response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
/**
* Shopify::_assign_libraries()
*
* Grab everything from the CI superobject that we need
*/
public function _assign_libraries()
{
$this->CI =& get_instance();
$this->CI->load->config('shopify', TRUE);
return;
}
UPDATE:
This whole line is started off by me calling this line of code:
$shopify = $this->shopify->shopify_api_client($shops_myshopify_domain, $shops_token);
I have also updated the code above to include the entire file.
You can achieve it only by passing $this as object to anonymous function, as it has its own context:
class example {
public function trigger() {
$func = $this->func();
$func($this);
}
public function func() {
return function($obj) {
$obj->inner();
};
}
public function inner() {
die('inside inner');
}
}
$obj = new example();
$obj->trigger();
EDIT: So in response to your problem:
Change this line:
return function ($method, $path, $params=array(), &$response_headers=array()) use ($baseurl)
into this:
return function ($instance, $method, $path, $params=array(), &$response_headers=array()) use ($baseurl)
Inside anonymous function change this line:
$response = curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
into this:
$response = $instance->curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
Now shopify_api_client function will return you this ANONYMOUS FUNCTION with no error:
$shopify = $this->shopify->shopify_api_client($shops_myshopify_domain, $shops_token);
You need to call this function in this way:
$shopify($this->shopify, ... AND HERE THE REST OF ARGUMENTS WHICH ANONYMOUS FUNCTION REQUIRE ...);
Is it clearer now? I have never used shopify, but general way it should work is as I wrote.
If your accessing a method from outside the class you need to state it, if your accessing the method from within the class you need use $this->methodname()
<?php
class shopify_api{
...
...
...
public function curl_http_api_request_($method, $url, $query='', $payload='', $request_headers=array(), &$response_headers=array())
{
$url = curl_append_query_($url, $query);
$ch = curl_init($url);
curl_setopts_($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response_headers = $this->curl_parse_headers_($message_headers);
return $message_body;
}
}
$shopify = new shopify_api();
//--------V
$response=$shopify->curl_http_api_request_();
?>
Since you have updated your question have you tried changing:
$shopify = $this->shopify->shopify_api_client($shops_myshopify_domain, $shops_token);
too: (as it seems your adding extra shopify property, i cant see from yourcode where you have set & injected your methods to it)
$shopify = $this->shopify_api_client($shops_myshopify_domain, $shops_token);

Categories