Getting JSON $_POST from FoxyCart Order Desk - php
I am trying to create a script to receive POST from FoxyCart's Order Desk. I setup a temporary request bin at requestb.in. When I pointed the POST there I get the new order JSON fine. I copy/pasted the JSON string in my script with this code I was able to parse the JSON and successfully added the variables to my database:
$string = "{"id":"1191583","email":"office#burntimpressions.com","shipping_method":"","quantity_total":1,"weight_total":0,"product_total":0,"shipping_total":0,"handling_total":0,"tax_total":0,"discount_total":0,"order_total":0,"cc_number_masked":"","cc_exp":"","processor_response":"","payment_type":"","payment_status":"Approved","processor_balance":0,"customer_id":"","email_count":"1","ip_address":"71.161.83.59","tag_color":"","source_name":"Order Desk","source_id":"1191583","fulfillment_name":"","fulfillment_id":"","tag_name":"","folder_id":6814,"date_added":"2015-06-14 16:53:54","date_updated":"2015-06-14 16:54:27","shipping":{"first_name":"Galen","last_name":"Dively","company":"Vermont Novelty Toaster Corporation","address1":"136 Bay Street","address2":"Ste 2","address3":"","address4":"","city":"Saint Johnsbury","state":"Vermont","postal_code":"05819","country":"US","phone":"(916) 448-5517"},"customer":{"first_name":"Galen","last_name":"Dively","company":"Vermont Novelty Toaster Corporation","address1":"136 Bay Street","address2":"Ste 2","city":"Saint Johnsbury","state":"Vermont","postal_code":"05819","country":"US","phone":"(916) 448-5517"},"checkout_data":[],"order_metadata":[],"discount_list":[],"order_notes":[],"order_items":[{"id":"2090400","name":"selfie test","price":0,"quantity":1,"weight":0,"code":"selfie","delivery_type":"ship","category_code":"","variation_list":[],"metadata":[]}],"order_shipments":[]}";
$order = json_decode($string, true);
$transactionId = $order [id];
$firstName = $order[customer][first_name];
foreach($order [order_items] as $p)
{
$cid = $p[id];
$productName = $p[name];
$code = $p[code];
$quantity = $p[quantity];
}
Order Desk's documentation says to get the POST with this:
$order = json_decode($_POST['order'], 1);
I am not getting anything. I have tried just about everything I can think of. Looked through this forum and have found nothing that will get the JSON parsed. I am assuming the POST was successful because I am not getting any errors from Order Desk's admin panel.
Order Desk has this code for security purposes. The POST seemed to pass all of them.
<?php
//Check For Order
if (!isset($_POST['order'])) {
header(':', true, 400);
die('No Data Found');
}
//Cbeck Store ID
//Be sure to set your store ID. Ask Order Desk support if you aren't sure what it is.
if (!isset($_SERVER['HTTP_X_ORDER_DESK_STORE_ID']) || $_SERVER['HTTP_X_ORDER_DESK_STORE_ID'] != "YOUR-STORE-ID") {
header(':', true, 403);
die('Unauthorized Request');
}
//Check the Hash (optional)
//The API Key can be found in the Advanced Settings section. Order Desk Pro only
if (!isset($_SERVER['HTTP_X_ORDER_DESK_HASH']) || hash_hmac('sha256', rawurldecode($_POST['order']), 'YOUR_API_KEY') != $_SERVER['HTTP_X_ORDER_DESK_HASH']) {
header(':', true, 403);
die('Unauthorized Request');
}
//Check Order Data
$order = json_decode($_POST['order'], 1);
if (!is_array($order)) {
header(':', true, 400);
die('Invalid Order Data');
}
//Everything Checks Out -- do your thing
echo "<pre>" . print_r($order, 1) . "</pre>";
Any help is greatly appreciated!
I guess I am asking how you would parse:
$order = json_decode($_POST['order'], 1);
What I get from requestb.in :
FORM/POST PARAMETERS
order: {"id":"1191583","email":"office#burntimpressions.com","shipping_method":"","quantity_total":1,"weight_total":0,"product_total":0,"shipping_total":0,"handling_total":0,"tax_total":0,"discount_total":0,"order_total":0,"cc_number_masked":"","cc_exp":"","processor_response":"","payment_type":"","payment_status":"Approved","processor_balance":0,"customer_id":"","email_count":"1","ip_address":"71.161.83.59","tag_color":"","source_name":"Order Desk","source_id":"1191583","fulfillment_name":"","fulfillment_id":"","tag_name":"","folder_id":6814,"date_added":"2015-06-14 16:53:54","date_updated":"2015-06-14 16:54:27","shipping":{"first_name":"Galen","last_name":"Dively","company":"Vermont Novelty Toaster Corporation","address1":"136 Bay Street","address2":"Ste 2","address3":"","address4":"","city":"Saint Johnsbury","state":"Vermont","postal_code":"05819","country":"US","phone":"(916) 448-5517"},"customer":{"first_name":"Galen","last_name":"Dively","company":"Vermont Novelty Toaster Corporation","address1":"136 Bay Street","address2":"Ste 2","city":"Saint Johnsbury","state":"Vermont","postal_code":"05819","country":"US","phone":"(916) 448-5517"},"checkout_data":[],"order_metadata":[],"discount_list":[],"order_notes":[],"order_items":[{"id":"2090400","name":"selfie test","price":0,"quantity":1,"weight":0,"code":"selfie","delivery_type":"ship","category_code":"","variation_list":[],"metadata":[]}],"order_shipments":[]}
HEADERS
Total-Route-Time: 0
Connect-Time: 1
X-Request-Id: 26eb3b73-bd15-4d75-9605-ea4fda0191dd
User-Agent: Guzzle/5.3.0 curl/7.19.7 PHP/5.5.21
X-Order-Desk-Store-Id: XXXXXXX
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 2228
Via: 1.1 vegur
Host: requestb.in
X-Order-Desk-Hash: XXXXXXXXXXXXX
Related
Retrieved JSON data not decoding to custom struct in xcode 12
I am currently in the process of learning how to retrieve encoded JSON data from a mySQL database on an apache server and decode the JSON into an instance of my own custom struct; struct Person: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64 var firstName: String var lastName: String } here is my method for the network request on xcode func dataRequestDownload() { let baseURL = URL(string: "http://example.com/db_request.php?action=request") DispatchQueue.main.async { if let url = baseURL { let task = URLSession.shared.dataTask(with: url) { data, response, error in if let data = data { let decoder = JSONDecoder() let person = try? decoder.decode(Person.self, from: data) print(person) } } task.resume() } } } } My issue is that person prints as nil which makes me think the data isnt being decoded properly. This is my PHP script for the GET request. <?php $con=mysqli_connect("127.0.0.1","root","example_password","example_database"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "SELECT * FROM person"; if ($result = mysqli_query($con, $sql)) { // If so, then create a results array and a temporary one // to hold the data $resultArray = array(); $tempArray = array(); // Loop through each row in the result set while($row = $result->fetch_object()) { // Add each row into our results array $tempArray = $row; array_push($resultArray, $tempArray); } // Finally, encode the array to JSON and output the results echo json_encode($resultArray); } // Close connections mysqli_close($con) ?> Finally I am not sure this info matters, but in the mySQL database the table is set up just like my struct where id is the PRIMARY key. If more information is needed let me know in the comments, but as far as I know this is all that seems connected to my issue. Edit: Some other possibly important information is when calling print(data) and print(response) I get 48 bytes { Status Code: 200, Headers { Connection = ( "Keep-Alive" ); "Content-Length" = ( 48 ); "Content-Type" = ( "text/html; charset=UTF-8" ); Date = ( "Thu, 17 Jun 2021 18:43:02 GMT" ); "Keep-Alive" = ( "timeout=5, max=100" ); Server = ( "Apache/2.4.46 (Win64) PHP/7.3.21" ); "X-Powered-By" = ( "PHP/7.3.21" ); } }) the URL is exempt from this of course. Per the request in the comments; having done this let object = try? JSONSerialization.jsonObject(with: data) print(object) I get Optional(<__NSSingleObjectArrayI 0x281510080>( { firstName = John; id = 0; lastName = Doe; } ) ) Edit2: Upon running do { let person = try decoder.decode([Person].self, from: data) print(person) } catch { print(error) } the following error appears typeMismatch(Swift.Int64, Swift.DecodingError.Context(codingPath [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode Int64 but found a string/data instead.", underlyingError: nil)) Here is the actual JSON upon visiting the URL [{"id":"0","firstName":"John","lastName":"Doe"}]
When decoding JSON, it's helpful to use do/try/catch so that you can actually see what the error is. It looks like, in this case, you have an array (which is clear from your PHP code), but you're trying to decode a single object. Try this: do { let person = try decoder.decode([Person].self, from: data) print(person) } catch { print(error) } Then, since you'll have an array in person (which might be more accurately named people at this point), you'll want to access it with something like person.first Update, based on added code in your edits: That error is telling you that id is a String in the JSON. Either adjust your Person model to use String for the type of id instead of Int64, or adjust your database and or PHP code to use a number instead of a String for the id.
Get total number of members in Discord using PHP
I have a Discord servern with 1361 members and on my website I want to display a total number of joined users. I have figured out how to get all online Members on the server using: <?php $jsonIn = file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json'); $JSON = json_decode($jsonIn, true); $membersCount = count($JSON['members']); echo "Number of members: " . $membersCount; ?> What should I do differently to get a total number of ALL users that have joined the server, and not just display the online members?
Now, I realize I am reviving a pretty old thread here, but I figure some might still use an answer. As jrenk pointed out, you should instead access https://discordapp.com/api/guilds/356230556738125824/members. Your 404: Unauthorized comes from the fact that you are -you guessed it- not authorized. If you have created a bot, it is fairly easy: just add a request header Authorization: Bot YOUR_BOT_TOKEN_HERE. If you use a normal Discord account, the whole problem is a bit more tricky: You will first have to send a POST request to https://discordapp.com/api/auth/login and set the body to {"email": "EMAIL_HERE", "password": "PASSWORD_HERE"}. You will get a response with the parameter token. Save this token, you will need it later. BUT: NEVER, UNDER ANY CIRCUMSTANCES show anyone this token, as it is equivalent to your login credentials! With this token, you can now send a POST request to the same address: https://discordapp.com/api/auth/login, but now add the header Authorization: YOUR_BOT_TOKEN_HERE. Note the missing "Bot" at the beginning. Also, what you mustn't forget: If you don't add the parameter ?limit=MAX_USERS, you will only get the first guild member. Take a look here to see details.
You have to count the number of online member here is the working code <?php $members = json_decode(file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json'), true)['members']; $membersCount = 1; foreach ($members as $member) { if ($member['status'] == 'online') { $membersCount++; } } echo "Number of members: " . $membersCount; ?>
You need a bot on your discord server to get all members. Use the Discord js library for example.
First create a discord bot and get a token, see the following url: https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token As #2Kreeper noted, do not reveal your token publicly. Then use the following code, replacing "enter-bot-token-here" and "enter-guild-id-here" with your own information: <?php $json_options = [ "http" => [ "method" => "GET", "header" => "Authorization: Bot enter-bot-token-here" ] ]; $json_context = stream_context_create($json_options); $json_get = file_get_contents('https://discordapp.com/api/guilds/enter-guild-id-here/members?limit=1000', false, $json_context); $json_decode = json_decode($json_get, true); echo '<h2>Member Count</h2>'; echo count($json_decode); echo '<h2>JSON Output</h2>'; echo '<pre>'; print_r($json_decode); echo '</pre>'; ?>
For anyone still interested, here's the solution I currently use using RestCord: use RestCord\DiscordClient; $serverId = <YourGuildId>; $discord = new DiscordClient([ 'token' => '<YourBotToken>' ]); $limit = 1000; $membercnt = 0; $_ids = array(); function getTotalUsersCount($ids, $limit, $serverId, $discord) { if( count($ids) > 0 ) { $last_id = max($ids); $last_id = (int)$last_id; } else { $last_id = null; } $members = $discord->guild->listGuildMembers(['guild.id' => $serverId, 'limit' => $limit, 'after' => $last_id]); $_ids = array(); foreach( $members as $member ) { $ids[] = $member->user->id; $_ids[] = $member->user->id; } if( count($_ids) > 0 ) { return getTotalUsersCount($ids, $limit, $serverId, $discord); } else { return $ids; } } $ids = getTotalUsersCount($_ids, $limit, $serverId, $discord); $membercnt = count($ids); echo "Member Count: " . $membercnt;
In addition to Soubhagya Kumar's answer comment by iTeY you can simply use count(), there is no need to loop if you do not require a loop.
I'm reviving this since it still seems to be relevant and the other answers seem a bit too complex I think (maybe the API used to be bad(?)). So: Generate a permanent discord invite and keep the code at the end (https://discord.gg/xxxxxxx) and then all you do is this: <?php $server_code = "xxxxxxx"; $url = "https://discord.com/api/v9/invites/".$server_code."?with_counts=true&with_expiration=true"; $jsonIn = file_get_contents($url); $json_obj = json_decode($jsonIn, $assoc = false); $total = $json_obj ->approximate_member_count; ?> And there you go, that's the total member count. Keep in mind, this will also count the bots I think so you have to account for that if you want to refine it even more
How can I fix this error implementing CommWeb on my website?
I am trying to implement CommWeb on my PHP site. It isn't working. I am getting following error message: HTTP Status - 400 E5000: Required field vpc_AccessCode was not present in the request How can I fix this? I haven't found anything helpful in the documentation. Here is my code: <?php //Merchant Admin URL: https://migs.mastercard.com.au/ma/CBA //Merchant ID: TEST //Operator ID: Admin //Password: d#test // Access Code AEFTEST 1A22FTESTTEST $session_id = 1; $finalprice = 50; $testarr = array( "vpc_Amount" => $finalprice*100,//Final price should be multifly by 100 "vpc_AccessCode" => "AEFTEST",//Put your access code here "vpc_Command"=> "pay", "vpc_Locale"=> "en", "vpc_MerchTxnRef"=> "CLI".$session_id, //This should be something unique number, i have used the session id for this "vpc_Merchant"=> "TEST",//Add your merchant number here "vpc_OrderInfo"=> "1A22FTESTTEST",//this also better to be a unique number "vpc_ReturnURL"=> "http://localhost/test1/index.php/commweb/",//Add the return url here so you have to code here to capture whether the payment done successfully or not "vpc_Version"=> "1"); ksort($testarr); // You have to ksort the arry to make it according to the order that it needs $SECURE_SECRET = "d#test";//Add the secure secret you have get $securehash = $SECURE_SECRET; $url = "https://migs.mastercard.com.au/ma/CBA"; foreach ($testarr as $key => $value) { $securehash .= $value; $url .= $key."=".urlencode($value)."&"; } $securehash = md5($securehash);//Encoding $url .= "vpc_SecureHash=".$securehash; header("location:https://migs.mastercard.com.au/vpcpay?$url"); ?>
How to get LINE user mid using PHP SDK?
I use the LINE BOT API Trial SDK PHP (https://github.com/line/line-bot-sdk-php). But, for this method: $res = $bot->sendText(['TARGET_MID'], 'Message'); How to get the user's MID to send them a message? Thanks for help.
1) A very quick way to get the mid of an interactive user (more of a fun hack, really) is to register a callback URL as per the API instructions, then capture the POST data to that URL like so: // /callback/index.php <?php $postdata = file_get_contents("php://input"); #file_get_contents('https://'.$_SERVER['SERVER_NAME'].'/LINE/' . json_encode($postdata)); Next, scan the QR code in the channel console and add your trial bot to your LINE account. After that is done, send it a quick "Hello!" text. You could then save the POST data to a text file if you wish, or you could check the server logs. For example, you might see something like this: 163.128.118.223 - - [03/Sep/2016:07:25:25 -0700] "POST /line/callback/ HTTP/1.1" 200 - "-" "ChannelEventDispatcher/1.0" 106.152.218.107 - - [03/Sep/2016:07:25:25 -0700] "GET /LINE/{\"result\":[{\"content\":{\"toType\":1,\"createdTime\":1472114754839,\"from\":\"ub7dbd4a12c322f6c0117773d739c55a4\",\"location\":null,\"id\":\"4357194057879\",\"to\":[\"u2b6a4ba287028dee7291122094dac827\"],\"text\":\"Hello!\",\"contentMetadata\":{\"AT_RECV_MODE\":\"2\",\"SKIP_BADGE_COUNT\":\"true\"},\"deliveredTime\":0,\"contentType\":1,\"seq\":null},\"createdTime\":1472912724868,\"eventType\":\"138311609000106301\",\"from\":\"u236d23c2e36bd87217655609a1c31cb8\",\"fromChannel\":1241102815,\"id\":\"WB1519-3102846635\",\"to\":[\"u2b6a4ba287028dee7291122094dac827\"],\"toChannel\":1462261375}]} HTTP/1.1" 404 15 "-" "-" The \"from\":\"ub7dbd4a12c322f6c0117773d739c55a4\" is the pertinent part. 2) If you'd like to get started with receiving messages, you can start like this as your callback script. Simply send your BOT the message 'mid' and it should respond with your mid. Here is a starting callback script I made with signature verification included for you. // /callback/index.php <?php // Show all errors for testing error_reporting(E_ALL); // SDK is installed via composer require_once __DIR__ . "/includes/vendor/autoload.php"; use LINE\LINEBot; use LINE\LINEBot\HTTPClient\GuzzleHTTPClient; // Set these $config = [ 'channelId' => LINE_CHANNEL_ID, 'channelSecret' => LINE_CHANNEL_SECRET, 'channelMid' => LINE_CHANNEL_MID, ]; $sdk = new LINEBot($config, new GuzzleHTTPClient($config)); $postdata = #file_get_contents("php://input"); $messages = $sdk->createReceivesFromJSON($postdata); // Verify the signature // REF: http://line.github.io/line-bot-api-doc/en/api/callback/post.html#signature-verification $sigheader = 'X-LINE-ChannelSignature'; // REF: http://stackoverflow.com/a/541450 $signature = #$_SERVER[ 'HTTP_'.strtoupper(str_replace('-','_',$sigheader)) ]; if($signature && $sdk->validateSignature($postdata, $signature)) { // Next, extract the messages if(is_array($messages)) { foreach ($messages as $message) { if ($message instanceof LINEBot\Receive\Message\Text) { $text = $message->getText(); if ($text == "mid") { $fromMid = $message->getFromMid(); // Send the mid back to the sender and check if the message was delivered $result = $sdk->sendText([$fromMid], 'mid: ' . $fromMid); if(!$result instanceof LINE\LINEBot\Response\SucceededResponse) { error_log('LINE error: ' . json_encode($result)); } } else { // Process normally, or do nothing } } else { // Process other types of LINE messages like image, video, sticker, etc. } } } // Else, error } else { error_log('LINE signatures didn\'t match'); }
DIBS recurring payment, no error message, not working at all
I am using the following code to work, but it is not working require('DIBSFunctions.php'); //Define input variables (here simply static variables) $Merchant = "123456"; $OrderID = "AHJ798123AH-BH"; $Currency = "208"; //DKK $Amount = "30000"; //In smallest possible unit 30000 Øre = DKK 300 $CardNo = "5019100000000000"; //DIBS test Dankort values $ExpMon = "06"; //DIBS test Dankort value $ExpYear = "13"; //DIBS test Dankort value $CVC = "684"; //DIBS test Dankort value $MD5['K1'] = "~.(S96%u|(UV,~ifxTt.DAKSNb&SKAHD"; //K1 and K2 MUST be gathered through $MD5['K2'] = "qJuH6vjXHLSDB*%¤&/hbnkjlBHGhjJKJ"; //ones DIBS admin-webinterface. //Call function DIBSAuth to authorise payment $RES = DIBSAuth($Merchant,$Amount,$Currency,$CardNo,$ExpMon,$ExpYear,$CVC,$OrderID,$MD5); echo '<pre>'; print_r($RES); //Check the response (the DIBS API returns the variable transact on success) if ( $RES['transact'] != "" ) { printf ("Authorisation successful! TransaktionID = %s",$RES['transact']); //Call function DIBSCapt to capture payment $RES2 = DIBSCapt($Merchant, $Amount, $RES['transact'], $OrderID); if ( $RES2['status'] == "ACCEPTED" ) { printf ("Transaction completed"); } else { printf ("Capture failed!"); } } else { printf ("Authorisation failed"); } This is the code output Array ( [reason] => 2 [status] => DECLINED ) Authorisation failed require('DIBSFunctions.php'); this file contains the username and password, I am providing it. e.g. function http_post($host, $path, $data, $auth="") { $auth['username'] = '123456'; $auth['password'] = '987656656'; //rest of the code } if someone wants to see the file 'DIBSFunctions.php' it can be downloadable from here http://tech.dibspayment.com/toolbox/downloads/dibs_php_functions/
i contact to the technical support and got the answer below: The problem you are experiencing is due to the fact that you are trying to send us real card numbers (test or live). This form of integration requires a PCI certification of your systems. Most customers use a so called hosted solution, where you use our payment windows. Please refer to tech.dibs.dk for documentation.