User id not coming in get_current_user_id() while running Custom endpoint post request - api

I am getting this issue while using custom endpoints. My entire functionality is based on get_current_user_id(). So, when I am running endpoint url it's not working through custom endpoint.
Even in init function user id is null. But when I print anything it working fine on site.
I am using this:
register_rest_route('v2', '/product/(?P\d+)/',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'wp_get_webhook_product',
)
);

Related

How to make CORS API call from Blazor client app with authentication using AutoRest Client?

I am trying to call Web API from Blazor Client App. The API sends required CORS headers and works fine when I call the API using plain Javascript.
The API needs Auth cookies to be included when making a call so using JavaScript I can call:
fetch(uri, { credentials: 'include' })
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log('Failed'));
Now, I am trying to do the same on Blazor. I came across this section on the docs which says:
requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
{
credentials = FetchCredentialsOption.Include
};
When I make a call now, it fails with following exception:
WASM: System.Net.Http.HttpRequestException: TypeError: Failed to execute 'fetch' on 'Window': The provided value '2' is not a valid enum value of type RequestCredentials.
I noticed that adding following on Statrup.cs allows me to call API including credentials (here):
if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
{
WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;
}
Now, I would like to call the API using AutoRest generated API Client so that I can reuse existing client and save lot of time. Setting DefaultCredentials as above doesn't work and shows following exception:
WASM: Microsoft.Rest.HttpOperationException: Operation returned an invalid status code 'InternalServerError'
Setting the requestMessage.Properties as above, says
The provided value '2' is not a valid enum value of type RequestCredentials`.
I am already injecting HttpClient from Blazor using this technique.
This is not really the answer... I just need space
Setting the requestMessage.Properties as above, says The provided
value '2' is not a valid enum value of type RequestCredentials
If so, what is wrong with the other method I suggested, which I guess is working.
Incidentally,
The provided value '2' is not a valid enum value of type
RequestCredentials
is not related to Blazor, right ? No such type (RequestCredentials) in Blazor. Perhaps your code, whatever it may be, gets the numeric value of the FetchCredentialsOption.Include and not its Enum string
Consider instantiating an HttpRequestMessage object, and configuring it according to your requirements.
Hope this helps...

Outlook webhook notification subscription

I already implemented outlook notification rest api into my code and its work fine but today it suddenly failed and gives me 400 error.
Request outlook for create subscription for notification
Output::
{"error":{"code":"ErrorInvalidParameter","message":"The parameter 'Resource' is invalid."}}
My post data as below ::
URL => outlook.office.com/api/v2.0/me/subscriptions
$subscriptionParameters = json_encode(array(
"#odata.type" => "#Microsoft.OutlookServices.PushSubscription",
"Resource" => "https://outlook.office.com/api/v2.0/me/events",
"NotificationURL" => "https://mydomain/acceptnotification.php",
"ChangeType" => "Created, Updated, Deleted",
"ClientState" => "c75831bd-fad3-4191-9a66-280a48528679"
));
Pass above data to outlook with access_token and email address using cUrl
Please suggest me.
Thank you for reporting this issue. Microsoft engineering team is investigating it right now. Meanwhile, a workaround that worked for multiple subscription cases is to use relative URL for the resource property
e.g.
"Resource": "me/events",
Thanks.

Best way to make restfull API in Laravel

I'm making a restfull API with Laravel 4 for an external website doing web scraping.
The target site has a login form so each request requires authentication.
If the user want to post or view something, he make a request to my server, that make another request to the target server, get the info, and encodes it in JSON.
My problem is how I get the credentials in my API request?
Now I have something like http://myapi.local/login (this make a request to http://externalsite.com/admin/login),
POST params are username=test&password=1234 and that returns a session ID
Then for every action, I append the session ID to my api requests
http://myapi.local/posts/all?session_id=4D2FtE...
But this is not restfull at all, so the best is to do it with HTTP Basic Auth, that is doing one login for each request
url: http://myapi.local/posts/all
header: Authorization: Basic dGVzdDoxMjM0
and call the login function in my controller.
It's slower because it makes two request to the target site each time, but seems better because I don't save any session or credentials.
How I handle the Authorization header in Laravel? decode base64 and then split credentials?
Is there a better way to do this?
Thank you!
Laravel handles basic auth himself, the only thing to do is think where you can use the filter (Laravel handles the basic auth with filters), so:
a) In a route:
Route::get('posts/all', array('before' => 'auth.basic', function()
{
// Only authenticated users may enter...
}));
b) Constructor in the controller (i prefer this):
function __construct() {
$this->beforeFilter('auth.basic');
}
Also make this adjust if apply for your case, as laravel docs say:
By default, the basic filter will use the email column on the user
record when authenticating. If you wish to use another column you may
pass the column name as the first parameter to the basic method in
your app/filters.php file:
Route::filter('auth.basic', function()
{
return Auth::basic('username');
});
Basic Auth Docs
EDITED
In your case then maybe you want implement a custom filter with this two methods as basis.
/**
* Get the credential array for a HTTP Basic request.
*/
function getBasicCredentials(Request $request, $field)
{
return array($field => $request->getUser(), 'password' => $request->getPassword());
}
/**
* Get the response for basic authentication.
*
* #return \Symfony\Component\HttpFoundation\Response
*/
function getBasicResponse()
{
$headers = array('WWW-Authenticate' => 'Basic');
return new Response('Invalid credentials.', 401, $headers);
}
See the default implementation here:

Send an email via MailChimp

I think problem is around $api->listSubscribers()
include('../libs/mailchimp/MCAPI.class.php');
$options = array('list_id' => '$list_id', 'subject' => 'Prova', 'from_name' => 'name', 'from_email' => 'info#example.com');
$content = array('html' => '<p>Testo di prova</p>');
$api = new MCAPI($apikey);
$campaignId = $api->campaignCreate('trans', $options, $content);
$api->listSubscribe($options['list_id']);
$api->campaignSendNow($campaignId);
if ($api->errorCode){
echo "Unable to Create New Campaign!";
echo "\n\tCode=".$api->errorCode;
echo "\n\tMsg=".$api->errorMessage."\n";
} else {
echo "New Campaign ID:".$campaignId ."\n";
}
Why does'nt it send an email?
You have a several issues here:
The first one is that you are not doing error checking after each API call. If you take the error checking code from the bottom and stick it after the listSubscribe() call, you'll immediately get an error because you aren't passing any sort of subscriber data (at the very least you need the email address). The docs for listSubscribe are here
Once you do that - unless you've thoroughly read and considered the options in the listSubscribe docs - your second issue is going to be that you are running listSubscribe with the double_optin parameter set to true (the default), which means they won't be subscribed until clicking a link in the confirmation email.
Next, that code is just going to get you in trouble, and probably quickly. If you are going to use psuedo-transcational campaigns it is imperrative that you only create ONE psuedo-trans campaign per type of email and then send that campaign over and over. That's how they are intended to work. Not doing that is going to cause you to fill up your account with a whole bunch of trash campaigns at which point there's no point in using a psuedo-trans campaign since that's the same as creating/sending a regular campaign to a single user over and over.
Do you get any errors?
It seems you are not including the api key, it should look like:
$api = new MCAPI($apikey);
Instead of:
$api = new MCAPI('apikey');
You get the API Key from your api dashboard: http://admin.mailchimp.com/account/api

SugarCRM 5.5.2 Rest api -- login failure

I need to be able to use the API for SugarCRM to exchange information with several other applications. I found the api docs, and some good articles with sample code. The end result of my code is to send this command:
http://localhost/sugarcrm/service/v2/rest.php?method=login&input_type=json&response_type=json&rest_data={%22user_name%22:%22rest%22,%22password%22:%2265e8800b5c6800aad896f888b2a62afc%22,%22version%22:%22.01%22}
Which produces this error
{"name":"Invalid Login","number":10,"description":"Login attempt failed please check the username and password"}null
I have googled the error and found several others with this issue, but no solution.
I think the proper REST string would be like:
method=login&input_type=json&response_type=json&rest_data={"user_auth": {"user_name":"user","password":"somemd5hash","version":"1.0"},"application_name":"RestTest"}
(should be url-encoded then of course)
For me, I needed to use something along the lines of:
method=login&input_type=JSON&response_type=JSON&rest_data=$REST_DATA
The REST data is:
{
user_auth => {
user_name => $USERNAME,
password => $PW,
version => "1.2"
},
application => "foo"
}
(URL encoded)
URL : http://mycrmurl.com/service/v4/rest.php
Request Data - in POST method
method=login&input_type=JSON&response_type=JSON&rest_data={"user_auth":{"user_name":"username","password":"md5password","version":"1.0"},"application_name":"RestTest"}
Response from WS:
{"id":"someID","module_name":"Users","name_value_list":{"user_id":{"name":"user_id","value":"1"},"user_name":{"name":"user_name","value":"username"},"user_language":{"name":"user_language","value":"en_us"},"user_currency_id":{"name":"user_currency_id","value":"-99"},"user_is_admin":{"name":"user_is_admin","value":true},"user_default_team_id":{"name":"user_default_team_id","value":null},"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"},"user_default_timeformat":{"name":"user_default_timeformat","value":"h:ia"},"user_number_seperator":{"name":"user_number_seperator","value":","},"user_decimal_seperator":{"name":"user_decimal_seperator","value":"."},"mobile_max_list_entries":{"name":"mobile_max_list_entries","value":null},"mobile_max_subpanel_entries":{"name":"mobile_max_subpanel_entries","value":null},"user_currency_name":{"name":"user_currency_name","value":"US Dollars"}}}