Walmart Api Integration with Laravel 7 and Auto Digital Signature Creation - laravel-7

I am working on Walmart Api Integration, using Laravel 7. I had installed the GuzzleHttp too. I used DigitalSignatureUtil.jar to generate WM_SEC.AUTH_SIGNATURE and WM_SEC.TIMESTAMP. It works fine to fetch data in json at first time. The following is the code.
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://marketplace.walmartapis.com/v3/feeds', [
'headers' => [
'WM_SVC.NAME' => 'walmart market place',
'WM_CONSUMER.ID' => '#########',
'WM_QOS.CORRELATION_ID' => '########',
'WM_CONSUMER.CHANNEL.TYPE' => '######',
'WM_SEC.AUTH_SIGNATURE' => '#######',
'WM_SEC.TIMESTAMP' => '1596290047006',
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
$products = json_decode((string) $res->getBody(), true);
return view('product', compact('products'));
NOTE: But it gives errors if i use the code next day, or after few minutes. I get following error
GuzzleHttp\Exception\ClientException
Client error: `GET https://marketplace.walmartapis.com/v3/feeds` resulted in a `401 Unauthorized`
response: {"error": [{"code":"UNAUTHORIZED.GMP_GATEWAY_API",
"field":"UNAUTHORIZED","description":"Unauthorized","info":"Unauthorize (truncated...)
Please help me what should i do to get rid from this?

Related

Capacitor Android fails to fetch from api

I'm trying to port my webapp to android by using capacitor.
I've got all but one part figured out.
Whenever I wanna get something from the databaser/server, i'm using fetch. And that works great in the browser - both on desktop and mobile.
But when I run the app through Android Studio, the fetch just fails with this error message
E/Capacitor/Console: File: http://localhost/ - Line 0 - Msg: Uncaught (in promise) TypeError: Failed to fetch
On the same device, but in the browser it works just fine.
I've tried adding a network-security-config.xml with the following
<network-security-config>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">http://5e4ce8849526.ngrok.io</domain>
</domain-config>
</network-security-config>
</network-security-config>
I've seen other people converting to HTTPS, but I couldn't get that to work either. This is for at school project due in a few days, so a timeconsuming process is not what I need.
Can it be caused by ngrok?
This is the fetch function running on load
let url = ' http://5e4ce8849526.ngrok.io'
function autoLogin(cb) {
let key = localStorage.getItem('userToken');
if(key == null || key == '') {
return 'No key stored';
} else {
fetch(url + '/informatik/readingapp/restapi/api/users/login.php', {
method: 'post',
headers: {
'Authorization': 'Bearer ' + key
},
})
.then(res => res.json())
.then((data) => {
console.log(data)
switch(data.message) {
case 'Password not verified':
presentAlert('Forkert kodeord', 'Har du skrevet dit kodeord rigtigt?')
break;
case 'Password verified':
nav.push('nav-home')
let tk = data.jwt.token
let usnm = data.username
let usid = data.id
cb(tk, usnm, usid);
break;
case 'No login data':
presentToastHome('Intet gemt login, desværre :(')
break;
}
})
}
}
I would appreciate any help :)
try to add
<Application android:usesCleartextTraffic="true">
in the AndroidManifest.xml of your app.
Since Api29 this is needed to do http request on android.

Cant`t insert Cyrillic symbols in POST fetch URL - NodeJS

Working on Telegram bot. A user sends requests from the bot to an external website API to get information. The very usual stuff.
I'm trying to make a POST request from NodeJS (Express) backend which contains cyrillic symbols
https://somewebsite.ru/api/v1/order.json?orderId=**МУЗ**008134
it says: TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters
Then I was trying to use ${encodeURIComponent(orderNumber)} instead of ${orderNumber}
Error checnged to
FetchError: invalid json response body at https://somewebsite.ru/api/v1/order.json?orderId=%D0%9C%D0%A3%D0%97008058 reason: Unexpected end of JSON input
When I use Postman there is no problem. I just put the whole URL https://somewebsite.ru/api/v1/order.json?orderId=МУЗ008134 and it works fine.
the server has utf8 encoding.
I'm using WebStorm and VS Code - both are set with UTF8
Here is the code:
oneOrder: async (orderNumber) => {
try {
let url = `https://somewebsite.ru/api/v1/order.json?orderId=${orderNumber}`
return fetch(url, {
method: 'post',
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
})
.then(res => res.json())
.then(answer => {
if (answer.error) {
return answer.message
} else if (answer.orderId) {
return `Номер заказа: ${answer['orderId']}\nСоздан ${answer['createdAt']}\nОбщая стоимость товаров в заказе: ${answer['totalCost']}\nСтатус оплаты: ${answer['status']['payment']}\nСтатус доставки: ${answer['status']['delivey']}`
}
return 'Нет информации по заказу'
})
} catch (e) {
console.log('ERROR with oneOrder function:', e)
}
},
...and, by the way, I have no idea why the "МУЗ008134" is not showed as a part of URL, but as a ppendix to the URL.
Thanks a lot and sorry if it seems to be too obvious.

Axios get response headers. Works in node, not in react

I will start off by saying this has nothing to do with authentication of JWT tokens.
I am trying to pull data from a public api. Lets call it www.abc.com/WeatherAPI.
When I do this in node with axios using axios.get(url), I am able to console.log(res.headers) and they show perfectly.( I need them for pagination and a recursive function)
When I use the EXACT SAME code in react, I get empty headers returned....
eg: content-type: "application/json"
date: "Sun, 08 Mar 2020 09:23:03 GMT"
Code:
return axios
.get(
'https://api.xxxxxxxx' +
(cursor ? '&cursor=' + cursor : '')
)
.then(res => {
console.log(res);
console.log(res.headers['cursor']);
// If there is no data, return...
if (res.data.length < 1) return;
// Push current data into OB state
setOB({ ...oB, ...res.data });
//te
//If there is no cursor... ie there is no more data, return
if (!res.headers['cursor']) return;
return OB(res.headers['cursor']);
});
};
// I dont know if use effect is right here... we will see..
useEffect(() => {
OB();
}, []);`
as the API is public, it could be that the response header differs based on the agent. it is not likely to be the case but it can be. I would suggest overriding the headers object including the User-Agent
axios.get(
`https://api.xxxxxxxx${cursor ? '&cursor=' + cursor : ''}`,
{ headers: { 'User-Agent': 'YOUR-SERVICE-NAME' } },
).then()...

Alexa Intent sends two requests and fails

What I am trying to do:
I have a very simple Alexa Skill which listens for a command word:
{
"intents": [{
"intent": "AffiliateEmpire",
"slots": [
{
"name": "affiliate_action",
"type": "AFFILIATE_ACTIONS"
},
{
"name": "date",
"type": AMAZON.DATE
}
}]
}
The custom slot type is:
AFFILIATE_ACTIONS commissions | earnings | sales | summary
My sample utterances are:
AffiliateEmpire for affiliate {affiliate_action}
AffiliateEmpire get {affiliate_action} for {date}
This communicates with my PHP server where I listen for the request type.
What is the problem?
When I invoke the command word without any intent, it makes a "LaunchRequest" to my server and correctly returns a card and outputSpeech
If I ask for an intent, it makes an IntentRequest to my server but then also sends a SessionEndedRequest.
I handle the IntentRequest and send it a json encoded response along the lines of:
array(
'version' => '1.0',
'response' => array(
'outputSpeech' => array(
'type' => 'PlainText',
'text' => 'Some simple response'
)),
'shouldEndSession' => true,
'sessionAttributes' => array()
));
My Amazon Echo never speaks the Some simple response but instead gives me There was a problem communicating with the requested skill
I had a very similar skill working before this, but cannot see what I am doing wrong.
What I have tried.
I am using php to write a log file for each raw request, json_decoded request and the response I sent back to Amazon. I am also using the testing tool, however this gives me The remote endpoint could not be called, or the response it returned was invalid.. I know it can call my endpoint as I see the log file written to each time.
Why is it calling my intent but then causing an error by ending the session?
Try the SSML for responding the alexa request,
Ex:
{
"version": "1.0",
"response": {
"directives": [],
"shouldEndSession": false,
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>I am going to book a cab for you # your provided time.</speak>"
}
}
}
The error you're getting... endpoint could not be called, or the response it returned was invalid suggests that the json you're sending back to the Alexa service is not formatted correctly. You're receiving the request, which is how it's getting logged. Now, you just need to troubleshoot the response your sending back. It's likely something minor. Here are the docs for the json response format: https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html. If you can share the json output from the php code it would be easier to help troubleshoot.
Also, I believe you need to change to 'shouldEndSession' => false
array(
'version' => '1.0',
'response' => array(
'outputSpeech' => array(
'type' => 'PlainText',
'text' => 'Some simple response'
)),
'shouldEndSession' => false,
'sessionAttributes' => array()
));

Status read failed in LWP Useragent

Case 1:
My server (accessing remotely does not have internet access) having the connectivity to the remote server in 443 port. Using web service URL, I need to send the web service request and receive the response. I am able to send the request using but unable to receive the response from remote server.
code:
Here is my code which i am using to send and receive the https request using the lwp agent in perl
use Data::Dumper;
use LWP::UserAgent;
use HTTP::Status;
use HTTP::Response;
use HTTP::Request::Common;
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
$LWPUserAgent = new LWP::UserAgent( 'timeout' => '20');
$LWPUserAgent->ssl_opts('verify_hostname' => 0) ;
$WEB_URL="https://webserviceurl.com/Request?Arg1|Arg2|Arg3|Arg4";
$Response = $LWPUserAgent->get($WEB_URL);
print Dumper $Response ;
I printed the response using Data::Dumper and getting below response.
$VAR1 = bless( {
'_content' => 'Status read failed: at /usr/share/perl5/Net/HTTP/Methods.pm line 269.',
'_rc' => 500,
'_headers' => bless( {
'client-warning' => 'Internal response',
'client-date' => 'Tue, 13 Oct 2015 15:13:21 GMT',
'content-type' => 'text/plain'
}, 'HTTP::Headers' ),
'_msg' => 'Status read failed: ',
'_request' => bless( {
'_content' => '',
'_uri' => bless( do{\(my $o = 'https://webserviceurl.com/Request?Arg1%7Arg2%7Arg3%7Arg4')}, 'URI::https' ),
'_headers' => bless( {
'user-agent' => 'libwww-perl/6.04'
}, 'HTTP::Headers' ),
'_method' => 'GET'
}, 'HTTP::Request' )
}, 'HTTP::Response' );
I searched more about this in google and i am unable to found any idea about this.
My server information are :
OS - wheezy 7.2 64bit.
perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-gnu-thread-multi
LWP::UserAgent - 6.04
HTTP::Response,HTTP::Status,HTTP::Request::Common versions are - 6.03.
Case 2: My server (in home and internet access) having the connectivity using my static ip of the internet connection. Using my proxy trying to run the above code with below piece of code.
$LWPUserAgent->proxy('https', 'http://192.168.12.10:3128') ;
I am able to send and receive the https requests using LWP agent and working fine.
My server information are:
OS - squeeze (6.0.6) 32 bit
perl, v5.10.1 (*) built for i486-linux-gnu-thread-multi
LWP::UserAgent - 6.13
HTTP::Response - 5.836
HTTP::Status - 5.817
HTTP::Request::Common - 5.824
I confused of the these things.
1.OS problem
2.Package versions problem
3.whether is it a bug in wheezy
If any one can provide me the correct direction to resolve this it would be highly appreciated.
Please set $ENV{HTTPS_DEBUG} = 1; and write here what the script prints.

Resources