how can i get additional $_GET Parameters in Yii2 even when prettyurl is enabled?
I need to read some feedback from the redirect Paypal-Link but i cant change the Link-Format on Paypal-Side to fit my Yii2 implementation:
http://example.com/controller/action?success=boolean&token=xyz
Thanks for your help!
you can use it
http://www.yiiframework.com/doc-2.0/guide-runtime-requests.html
for e.g
if you need to use $_GET['success'] or $_GET['token']
you must use it:
$request = Yii::$app->request;
$get = $request->get();
$success = $request->get('success');
$token= $request->get('token');
I figured out a way:
$url = parse_url(Yii::$app->request->url);
parse_str($url['query'], $array);
$success = $array['success'];
$token = $array['token'];
but it still doesnt seem like the right Yii2-ish way to solve it.
http://www.yiiframework.com/doc-2.0/yii-web-urlmanager.html this will help You. you can specify GET POST method for any controller,
[
'dashboard' => 'site/index',
'POST <controller:\w+>s' => '<controller>/create',
'<controller:\w+>s' => '<controller>/index',
'PUT <controller:\w+>/<id:\d+>' => '<controller>/update',
'DELETE <controller:\w+>/<id:\d+>' => '<controller>/delete',
'<controller:\w+>/<id:\d+>' => '<controller>/view',];
for example
'POST <controller:\w+>/<success:\w+>/<token:\w+>' => '<controller>/update',
Use the Request class.
http://www.yiiframework.com/doc-2.0/yii-web-request.html
print_r(Yii::$app->request->get()); returns all get variables in an array. It's like doing print_r($_GET); in straight php.
If you want a specific $_GET variable you access it as follows:
Yii::$app->request->get('varName');
In your case it would be:
$success = Yii::$app->request->get('success');
$token = Yii::$app->request->get('token');
Here is my successful returnUrl from paypal which yii2 handles beautifully with prettyurl enabled in the UrlManager.
http://multi2.myhost/subscription/subscription/success?token=EC-8GE539098H175763M
I have created a subscription module and a controller class called SubscriptionController and actions called actionSuccess and actionCancel.
The Paypal redirect only passes one parameter. The token. No need for two parameters. Your success and cancel returnurl's should be something like:
controller/action or subscription/success/
controller/action or subscription/cancel/
Your success returnUrl:
SubscriptionController/actionSuccess($token)
public actionSuccess($token)
{
}
and your cancel returnUrl:
SubscriptionController/actionCancel($token)
public actionCancel($token)
{
}
Using this method there is no need for a second parameter to handle the success and cancel variable since the separate Controller Actions solve this problem. Incorporate the 'success' in the name of the action which satisfies PrettyUrl Management.
You will have to modify both merchant preference returnUrls in the following code.
$merchantPreferences = new MerchantPreferences();
$merchantPreferences->setReturnUrl($model->merchant_preference_returnurl)
->setCancelUrl($model->merchant_preference_cancelurl)
There is therefore no need for:
$request = Yii::$app->request;
$get = $request->get();
$token = $request->get('token');
at the beginning of the action.
Related
I have registered a api request the following way in the code, then in postman I call that request and add some params, but when I run the api request endpoint it returns null.
How do I return the data that's being sent?
/**
* This is our callback
* function that embeds our phrase in a WP_REST_Response
*/
function addProductFromCRM($data) {
//$name = $data['name'];
// rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.
return rest_ensure_response($data);
}
/**
* This function is where we register our routes for our example endpoint.
*/
function wp_register_crm_routes() {
// register_rest_route() handles more arguments but we are going to stick to the basics for now.
register_rest_route('crm/v1', '/addproduct/', array(
// By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
'methods' => 'POST',
// Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
'callback' => 'addProductFromCRM',
));
}
add_action('rest_api_init', 'wp_register_crm_routes');
What addproduct endpoint should return? JSON? You can do something like this:
function addProductFromCRM($request) {
wp_send_json($request->get_params());
}
You can use below code snippet as per you need like on isset($_POST) or any other callback function. You must have the idea of your Register Route URL and must be working. you can use wp_remote_get or wp_remote_post as per your need. for more reference please check WordPress official site
$response = wp_remote_get("URL TO YOUR REGISTER ROUTE");
if ( is_array( $response ) ) {
$response_code = wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
$body_data = json_decode($body);
}
I am trying to find the logged in user in my application using Auth but i get trying to get property of non-object which i understand clearly that it is returning null.
In my code below, an event triggers my webhook and post is sent to the address below. The function orderCreateWebhook triggers but that is where the error comes from..
The line $get_template = Order::where('id', Auth::user()->id);. Why is Auth returning null please? I am logged as well because i use auth in this same controller for another function which works fine.
Is it because it a webhook ?
Controller
public function registerOrderCreateWebhook(Request $request)
{
$shop = "feas.myshopify.com";
$token = "8f43d89a64e922d7d343c1173f6d";
$shopify = Shopify::setShopUrl($shop)->setAccessToken($token);
Shopify::setShopUrl($shop)->setAccessToken($token)->post("admin/webhooks.json", ['webhook' =>
['topic' => 'orders/create',
'address' => 'https://larashop.domain.com/order-create-webhook',
'format' => 'json'
]
]);
}
public function orderCreateWebhook(Request $request)
{
$get_template = Order::where('id', Auth::user()->id);
$baseurl = "https://apps.domain.net/smsapi";
$query = "?key=7e3e4d4a6cfebc08eadc&to=number&msg=message&sender_id=Shopify";
$final_uri = $baseurl.$query;
$response = file_get_contents($final_uri);
header ("Content-Type:text/xml");
}
In your function registerOrderCreateWebhook you appear to be making a request to shopify api and providing your webhook as the address which shopify will redirect the user to upon success. If this is correct, that request does not know about the user who generated the original request that made the api request since the request is coming from a completely different origin.
You would need to pass some key along with the url and then obtain the user within orderCreateWebhook. Something like:
Shopify::setShopUrl($shop)->setAccessToken($token)->post("admin/webhooks.json",
['webhook' =>
['topic' => 'orders/create',
'address' => 'https://larashop.domain.com/order-create-webhook/some-unique-key',
'format' => 'json'
]
]);
My suggestion would be to have a unique hash stored somewhere that relates back to the user in your system, perhaps a column in your users table. I wouldn't use the user_id for security reasons. So you would end up with something like:
//route
Route::get('/order-create-webhook/{uniqueKey}', 'YourController#orderCreateWebhook');
//or
Route::post('/order-create-webhook/{uniqueKey}', 'YourController#orderCreateWebhook');
// depending on the request type used by api which calls this endpoint
// controller function
public function orderCreateWebhook($uniqueKey, Request $request)
{
$user = User::where('unique_key', $uniqueKey)->first();
$get_template = Order::where('id', Auth::user()->id);
$baseurl = "https://apps.domain.net/smsapi";
$query = "?key=7e3e4d4a6cfebc08eadc&to=number&msg=message&sender_id=Shopify";
$final_uri = $baseurl.$query;
$response = file_get_contents($final_uri);
header ("Content-Type:text/xml");
}
Is it because it a webhook ?
Yes, you can't use sessions in a webhook. It's the shopify server which is making the call. You should read the doc, it may exist a way to give an unique identifier in your call to shopify api and get it back in the webhook to find your user associated.
just use this to get authenticated user
use the facade in your class/Controller
use Illuminate\Support\Facades\Auth
public function getAuthUser(){
$user = Auth::user()
if(!is_null($user)
{
//user is authenticated
}
else
{
// no user
}
}
I want to setup callback url for blockchain.info receive api.
Below is a php example but i don't know to to setup this in laravel
$my_callback_url = 'https://mystore.com?invoice_id=058921123&secret='.$secret;
my route is following
Route::get('btc_ipn/{invoice_id}/{secret}',['as'=>'btc_ipn','uses'=>'HomeController#btcIPN']);
I tried but ipn doesn't work.
If you want to build URL for the route you've shown, do something like this:
$url = route('btc_ipn', ['invoice_id' => $invoice->id, 'secret' => $secret]);
If you need to create a route for this URL:
https://mystore.com?invoice_id=058921123&secret=' . $secret;
Create a get or post route:
Route::get('/', 'HomeController#btcIPN');
Then in the controller:
public function btcIPN()
{
$invoiceId = request('invoice_id');
$secret = request('secret');
}
To meet routes you created as
Route::get('btc_ipn/{invoice_id}/{secret}',['as'=>'btc_ipn','uses'=>'HomeController#btcIPN']);
Your url should be like
$invoice_id = $request->invoice_id;
$secret = $request->secret;
$my_callback_url = "/btc_ipn/$invoice_id/$secret";
If you want to return with some data like error use
return redirect()->back()->withErrors(['msg', 'The Message']);
My Controler
function actionLogin()
{
//After success validation
$url = $_POST['returnUrl']; // www.example.com/get_response/
$arr = array('response' => 'Failed', 'msg' => 'login success','tokenKey'=> 'token');
//How to send the response to url
}
In my above code i have to send the $arr array to $url absolute URL.
I found some solutions for this is it works here?
Yii::$app->getResponse()->redirect('http://newdomain.com');
But i don't know how to use in my case or is there any better way
In controller, use:
$this->redirect("absolute URL");
If you want redirect to a specific action:
$this->redirect(array('controller/action'));
we can use getBaseUrl to get absolute url
$this->redirect(Yii::app()->getRequest()->getBaseUrl(true));
Here you can read how to redirect in Yii.
Following code should work for you:
function actionLogin()
{
//After success validation
$url = $_POST['returnUrl']; // www.example.com/get_response/
$arr = array('response' => 'Failed', 'msg' => 'login success', 'tokenKey' => 'token');
//How to send the response to url
$this->redirect('http://' . $url . '?' . http_build_query($arr));
}
You have to build your http query by your own. Yii does not support any function that helps you to create outbound urls with query parameters.
I have taken over an application from a previous developer, and there was some code which was half finished using Nusoap, I am getting the error:
Call to register_donation() web service failed due to an exception:
Function ("register_donation") is not a valid method for this service
The application is built on: CakePHP 1.2.10 & using nuSoap 0.9.5.
I have already ini_set('soap.wsdl_cache_enabled', 0); (This doesnt help.)
My code is below (I shortened it for readability), Am I processing this response correctly?
(The code was taken over by myself from a previous developer).
The Pastebin (of the full code) is here: PasteBin Link
A shortened version is below for a glance over, the full version is in the pastebin link above.
<?php
ini_set('soap.wsdl_cache_enabled', 0);
class ServicesController extends AppController
{
var $uses = array("Donation");
var $components = array( "Email", "MatchingEvents" );
function registerDonation($donation = null){
$this->log('hit registerDonation', 'donation');
$this->autoRender = false;
App::import('Vendor','nusoap');
Configure::write('debug',0);
Configure::write('Session.start', false);
//init soap server
$server = new soap_server();
$endpoint = 'http://new.mysite.com/services/registerDonation';
//initialize WSDL support
$server->configureWSDL('donations', 'urn:donations', $endpoint);
//setup service type
$server->wsdl->addComplexType(
'DonationResult',
'complexType',
'struct',
'all',
'',
array(
'success' => array('name' => 'success', 'type' => 'xsd:boolean'),
'msg' => array('name' => 'msg', 'type' => 'xsd:string'),
'error_number' => array('name' => 'error_number', 'type' => 'xsd:string')
)
);
//register the method to expose
$server->register('register_donation',
array('ct_number' => 'xsd:string', 'project_id' => 'xsd:int', 'donation_amount' => 'xsd:decimal',
// Stripped all other params
),
array(
'result' => 'tns:DonationResult'
),
'urn:donations',
'urn:donations#register_donation',
'rpc',
'encoded',
'Accepts the results of a donation to a charity or project on the site'
);
//This inner function is registered and then called (keep within outer function!)
function register_donation(
// Pass in all the params (Stripped for readability)
$ct_number = null, $project_id = null, $donation_amount = null
){
// This function is never hit!.. its not registered, why?
$this->log('hit #3-register_donation called!', 'donation');
$return = $this->Donation->add(array(
'unique_id' => $unique_id,
'ct_number' => $ct_number,
'project_id' => $project_id,
'donation_amount' => $donation_amount,
// Pass in all other params, (Stripped for readability)
));
// Process that request
$log = $this->Donation->log . 'Result: ' . $return['msg'] . "\n";
$this->log( $log, 'donation' );
if ( isset($this->Donation->matching['events']) )
{
//Reserved donations should already have had their events handled
$this->MatchingEvents->handle($this->Donation->matching, !$this->Donation->matching['reserved']);
}
if ( !empty($this->Donation->cacheSaved) )
$this->_sendDonationEmails($this->Donation->cacheSaved);
return $return;
}
$HTTP_RAW_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
$server->service($HTTP_RAW_POST_DATA);
}
function _sendDonationEmails($donation)
{
// Send the emails
}
}
?>
If there is any more information I can provide, please let me know.
To Summarise: How do I process a nusoap response coming from a external source.
Any debugging ideas, hints & tips or solution will be rewarded (+1!).
In the code posted there's a function named registerDonation inside a controller named ServicesController. Inside that function there is another function called register_donation (This obviously doesn't make sense [Old Code]).
Remove the function named register_donation out of the registerDonation method and place it as a method inside the ServicesContoller.
Then change the following line (where you register the function to expose).
From: $server->register('register_donation',
To: $server->register('ServicesController.register_donation',
So you're calling class.method as opposed to method only (This would work in PHP4 procedural programming, but in OOP, you need to specify the controller.method when exposing the function).
Having other problems?
Q: CakePHP & nuSOAP is not hitting my controller/method, but redirects to app/webroot
A: Using CakePHP 1.2, I found when it did not have a services model (because it wasn't
technically required), The request does not hit the controller. So if you're having this issue, create a model for your controller, even if you're not using it. For your reference, here a modal example:
<?php // You may not need this modal, but cakephp requires it to be there.
class Services extends AppModel {
public $name = 'Services';
public $useTable = false;
}
?>
Q:What URL should I be receiving responses to?
A: The URL you set your response to hit must include ?wsdl.
So.. for eg: you have a controller named SOAPController and method named process.
In CakePHP, your URL would look like this: mydomain.com/SOAP/process.
So your WSDL is located at mydomain.com/SOAP/process?wsdl. Make sure your callback URL is set to this (including the wsdl).
Q: How do I debug SOAP requests/responses using CakePHP?
A: CakePHP has a logging feature which proved invaluable in debugging SOAP. In your controller (or modal) you can use:
$this->log('your message or variable', 'name_of_file_to_save_to);
You can use this through your SOAP request or response to see what parts are being hit/called and debugging variables (eg: $HTTP_RAW_POST_DATA).
Q: My WSDL location is shown as `domain.com/app/webroot` when I visit the SOAP page.
A: I thought this was the issue causing all the problems, Looking at the source code Nusoap uses PHP_SELF to get the current script (which in cakePHP is app/webroot/index.php), Don't worry about this, you can access the wsdl by appending the URL with ?wsdl, This will show you your generated WSDL file, You don't need to worry about fixing this. Its not interfering with your SOAP request whatsoever, It's merely there for your convenience.
Q: My SOAP address location is showing 'domain.com/app/webroot/index.php`
A: This was a issue I fixed by including the $endpoint in the configureWSDL().
//Set our endpoint, Replace with your URL
$endpoint = 'http://yourdomain.com/controller/method';
//initialize WSDL support - Include the $endpoint.
$server->configureWSDL('donations', 'urn:donations', $endpoint);
// Now your Soap Address Location should be what you set as the $endpoint