401 unauthorized ajax call error to Watson Assistant API - javascript

I am trying to make ajax request to Watson Assistant API from client side only, so I had this code in php which is working fine but when I tried to make it in jQuery I got 401 unauthorized error.
PHP:
$data['input']['text'] = $_POST['message'];
if(isset($_POST['context']) && $_POST['context']){
$data['context'] = json_decode($_POST['context'], JSON_UNESCAPED_UNICODE);
}
$data['alternate_intents'] = false;
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
// Post the json to the Watson API via cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://watson-api-explorer.mybluemix.net/conversation/api/v1/workspaces/'.$workspace_id.'/message?version='.$release_date);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = trim( curl_exec( $ch ) );
curl_close($ch);
// Responce the result.
echo json_encode($result, JSON_UNESCAPED_UNICODE);
JS:
$.ajax({
url: apiUrl,
type: 'POST',
dataType: 'json',
data: {
message: message,
context: context
},
headers:{
'Authorization' : 'Basic' + btoa('f7be829c-ae6d-47d8-b2bd-65a40ad45aa' +':'+ 'hJcToxQ23Zk'),
},
contentType: 'application/json',
timeout:10000
})
Anything missing from the JS code?
Note: credentials mentioned are for example only.

Related

How can i implement paypal checkout v2 server side / JS sdk

I'm trying to make an implementation for paypal using checkout.js, however, i need to store the details of the transaction once the payment it's completed but first, i'm having trouble getting the button values from the server side, my code goes as follows:
<script>
paypal.Buttons({
// Order is created on the server and the order id is returned
// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch('php/create.php', {
method: 'post'
}).then(function(response) {
return response.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Call your server to save the transaction
return fetch('/paypal-transaction-complete.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: details.id
})
});
});
}
}).render('#paypal-button-container');
</script>```
<?php session_start();
// PayPal configuration
define('PAYPAL_CONFIG', [
'URL' => "https://api-m.sandbox.paypal.com/",
'CLIENT_ID' => 'xxx',
'SECRET' => 'xxx',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, PAYPAL_CONFIG['URL'] . "v2/checkout/orders");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, PAYPAL_CONFIG['CLIENT_ID'] . ":" . PAYPAL_CONFIG['SECRET']);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = [
"intent" => "sale",
"redirect_urls" => [
"return_url" => "http://localhost:8888/index.php",
"cancel_url" => "http://localhost:8888/index.php"
],
"payer" => [
"payment_method" => "paypal"
],
"transactions" => [
[
"amount" => [
"total" => $_SESSION['price'],
"currency" => "USD"
]
]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$response = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Invalid JSON response: " . json_last_error_msg());
var_dump($httpStatusCode);
return false;
}
if (!$result) {
error_log("cURL request failed with HTTP status code: " . $httpStatusCode);
var_dump($httpStatusCode);
return false;
}
return $result;
Whenever i try to click the paypal button, i keep getting a console error saying that Error: Unexpected end of Json input and closes the paypal window almost immediately
I've tried debbuging with several methods but i can't get it working, any suggestions?
(That code is not for checkout.js , which is older and deprecated ; you're using the current PayPal JS SDK)
Anyway, this issue:
Error: Unexpected end of Json input
Occurs when your server-side code is outputting something other than a purse JSON string, such as a var_dump or other echo statement. Your create and capture routes must output only a JSON string, never any other text or HTML.
You can get a log of the response being outputted to the XHR request in your browser's dev tools -> Network tab.

Unable to run Discord slash command using Php

I am working with php and "Discord", Whenever i type manual command("/imagine prompt ANYTEXT") in discord then i am getting image, i want exactly same process with php but whenever i try
do this then i am not getting any iamge,Only exact command displaying in chatbot instead of displaying image,Here is my current code
$url = "https://discord.com/api/webhooks/MYWEBHOOK";
$hookObject = json_encode([
"embeds" => [
[
"title" => "/imagine prompt nature",
]
]
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
$headers = [ 'Content-Type: application/json; charset=utf-8' ];
$POST = [ 'username' => 'Testing BOT', 'content' => 'Testing message' ];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $hookObject);
$response = curl_exec($ch);

Convert from curl to ajax

I would like to get some help with my ajax code. I want to move the curl code in the index.html to work with ajax but I don't know how I can convert from curl to ajax code.
Index.html:
<script>
$button.click(function(e)
{
e.preventDefault();
var emptyMail = true;
var email = $emailInput.val().trim();
var $emailInput_1 = $("#email").val();
$(document).ready(function()
$(this).val("SUBMITTING...");
$("form").submit();
$.ajax({
url: "post.php",
type: 'POST'
});
});
</script>
Here is the post.php
<?php
function _curl($url, $post = "", $headers = "")
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_POST, ($post && is_array($post))? 1 :0);
if ($post && is_array($post))
{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
}
if ($headers && is_array($headers))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/dev/null");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
return $result;
curl_close($ch);
}
if ($_POST)
{
_curl("http://example.com/land/formFillReturnV5b.php", array(
"name"=>"groups_name",
"email"=>$_POST['email'],
"phone"=>"",
"ip"=> $_SERVER['SERVER_ADDR'],
"reff"=>"",
"page"=>"Q6",
"link"=>"https://example.com/meme",
"notes"=>"",
"MID"=>"39918",
"LID"=>"",
"ARData"=>"meme",
"cookie"=>""), array("X-NewRelic-ID" => "VQQBVl9aDRABUFJbAQkOUQ==", "X-Requested-With" => "XMLHttpRequest", "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"));
}
?>
I want to make it like this:
<script>
$button.click(function(e)
{
e.preventDefault();
var emptyMail = true;
var email = $emailInput.val().trim();
var $emailInput_1 = $("#email").val();
$(document).ready(function()
$(this).val("SUBMITTING...");
$("form").submit();
$.ajax({
url: "http://example.com/land/formFillReturnV5b.php",
type: 'POST',
"name"=>"groups_name",
"email"=>$_POST['email'],
"phone"=>"",
"ip"=> $_SERVER['SERVER_ADDR'],
"reff"=>"",
"page"=>"Q6",
"link"=>"https://example.onlinesalespro.com/meme",
"notes"=>"",
"MID"=>"39918",
"LID"=>"",
"ARData"=>"meme",
"cookie"=>""), array("X-NewRelic-ID" => "VQQBVl9aDRABUFJbAQkOUQ==", "X-Requested-With" => "XMLHttpRequest", "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"));
});
});
</script>
When I tried it, it won't work. If you can show me an example how I can use ajax code to send the data to the server that would be great.
Used Documentation
Example code
<script>
$button.click(function(e)
{
e.preventDefault();
var emptyMail = true;
var email = $emailInput.val().trim();
var $emailInput_1 = $("#email").val();
$(document).ready(function()
$(this).val("SUBMITTING...");
$("form").submit();
$.ajax({
url: "http://example.com/land/formFillReturnV5b.php",
type: 'POST',
data: {name: "groups_name", email: "text#email.ru" /* and other parametrs*/ }
success: function(result) {
console.log(result);
}
});
});
</script>

PHP Simple HTML DOM with POST method?

How to use Simple HTML DOM with input POST method?
I try to do with cUrl:
$ch = curl_init();
$timeout=5;
$data = array('teks' => '4ia17');
$data=http_build_query($data);
curl_setopt($ch,CURLOPT_URL,"http://baak.gunadarma.ac.id/jadwal/cariJadKul");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$datas = curl_exec($ch);
curl_close($ch);
echo $datas;
the problem is :
problem
and i try to do this too
include("simple_html_dom.php");
$request = array(
'http' => array(
'header' => array("Content-Type: application/x-www-form-urlencoded"),
'method' => 'POST',
'content' => http_build_query(array(
'teks' => '4ia17'
)),
)
);
$context = stream_context_create($request);
$htmls = file_get_html("http://baak.gunadarma.ac.id/jadwal/cariJadKul",true, $context);
echo $htmls;
and the error is :
Warning: file_get_contents(http://baak.gunadarma.ac.id/jadwal/cariJadKul): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in C:\xampp\htdocs\php-youtube-dl-master\Downloader\simple_html_dom.php on line 75
can anyone please help me where lies the error is? or something i can do with?

Use a PHP variable in Javascript / Ajax without showing in the inspect element

i want to send emails with de mandrill api. I have mi apikey in a php var but when i do var apikey='<?php echo$apikey;?>'; this shows in the inspect elemnt.
its posibble hide, encrypt or something the variable with php, javascript, ajax or json?
this is and example of my code:
<?php
$apikey='aaaaaaaaaaaaaa';
?>
<script type="text/javascript">
var apikey='<?php echo$apikey;?>';
sendEmail();
function sendEmail() {
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': apikey,
'message': {
'from_email': 'FROM_EMAIL_GOES_HERE',
'to': [{
'email': $('.email').val(), // get email from form
'name': $('.name').val(), // get name from form
'type': 'to'
}
],
'autotext': 'true',
'subject': 'EMAIL_SUBJECT_GOES_HERE',
'html': "Hey *|COOLFRIEND|*, we've been friends for *|YEARS|*.", // example of how to use the merge tags
'track_opens': true,
'track_clicks': true,
}
}
}).done(function(response) {
console.log(response); // if you're into that sorta thing
});
});
</script>
You can setup a php service and use curl to do the transferring work. Then just have AJAX do the front end work and send the subject/body/etc to the php service.
#Lifz works great for me
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$result = curl_exec($ch);

Categories

Resources