A JSON object containing a PHP variable

I'm trying to integrate a PHP variable into my PayPal single payout call code where the price is defined at 'value':".$planPrice." When I manually input a number like "1000", it works fine and I receive the notification. However, when I use the PHP variable, I encounter this error message:

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Invalid JSON String' in C:\xampp\htdocs\website\paypal_payouts\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Validation\JsonValidator.php:29 Stack trace: #0 C:\xampp\htdocs\website\paypal_payouts\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Common\PayPalModel.php(50): PayPal\Validation\JsonValidator::validate('{\r\n ...') #1 C:\xampp\htdocs\website\paypal_payouts\CreateSinglePayout.php(67): PayPal\Common\PayPalModel->__construct('{\r\n ...') #2 C:\xampp\htdocs\website\admin\reports\paynow.php(19): include('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\website\paypal_payouts\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Validation\JsonValidator.php on line 29

Here is the PHP code snippet:

$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
    ->setNote('Thanks for your patronage!')
    ->setReceiver($coachUsername)
    ->setSenderItemId("2014031400023")
    ->setAmount(new \PayPal\Api\Currency("{
                        'value':".$planPrice.",
                        'currency':'USD'
                    }")); 

Answer №1

Instead of passing a JSON string to Paypal\Api\Currency, it is recommended to use an array for simplicity:

$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
    ->setNote('Thanks for your patronage!')
    ->setReceiver($coachUsername)
    ->setSenderItemId("2014031400023")
    ->setAmount(new \PayPal\Api\Currency([
                        'value' => $planPrice,
                        'currency' => 'USD'
                    ]));

However, if JSON must be used, ensure that it is valid. JSON specifically requires the use of double quotes for strings and key names:

$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
    ->setNote('Thanks for your patronage!')
    ->setReceiver($coachUsername)
    ->setSenderItemId("2014031400023")
    ->setAmount(new \PayPal\Api\Currency('{
                        "value":'.$planPrice.',
                        "currency":"USD"
                    }'));

(Assuming that "value" should be assigned a JSON number. If it needs to be a JSON string, replace the third-to-last line with "value": "' . $planPrice . '", instead.)

Answer №2

It is strongly advised to avoid manually generating JSON.

Instead, utilize the PHP function json_encode(). This function handles quotes, commas, matching parentheses, and more:

$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
    ->setNote('Thanks for your patronage!')
    ->setReceiver($coachUsername)
    ->setSenderItemId("2014031400023")
    ->setAmount(
        new \PayPal\Api\Currency(
            json_encode(array(
                'value'    => $planPrice,
                'currency' => 'USD',
            ))
        )
    );

Additionally, there is no need to manually generate JSON. You can create a new PayPal\Api\Currency object and use its methods like setValue() and setCurrency() to set its properties.

$amount = new \PayPal\Api\Currency();
$amount->setValue($planPrice);
$amount->setCurrency('USD');

$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
    ->setNote('Thanks for your patronage!')
    ->setReceiver($coachUsername)
    ->setSenderItemId("2014031400023")
    ->setAmount($amount)
;

If you are unfamiliar with the PayPal API, it is common practice to construct objects using the response received from the server. Therefore, it's recommended to instantiate empty objects and then set their properties (similar to how you handle $senderItem) when constructing a request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for switching on and off responses for initial level comments?

Is there a way to manage long comments and replies on my website's nested comment system? I attempted to Hide/Toggle replies upon page load using Ajax, but it was unsuccessful. I added an id to the child comments container and used code to achieve th ...

PHP - The memory limit has been exceeded with 134217728 bytes allocated

Here is a snippet of code that I'm currently working with: <?php namespace Debug; function Alert($msg){ $temp = "<script>alert('".$msg."')</script>"; echo $temp; } function Log($msg){ $temp = "<script>consol ...

The modifications made to the Laravel 4.2 website do not appear to be taking effect as expected

I am a beginner with the laravel framework and I'm currently working on editing a laravel web application. The website is hosted on an EC-2 instance of AWS and I am using SCP with filezilla for file transfer. Upon investigating, I discovered that th ...

Is it possible to modify a request header in Spring Boot on the HttpServletRequest object?

Is there a way to automatically set the content-type header as application/json in the HttpServletRequest when it is not provided by the user? I have been trying to validate this, but so far I haven't found any suitable methods for achieving this. ...

saving information into a MySQL database

I am facing an issue where I am trying to write data to MySQL. When I input the data and press the submit button, the console log message from the function indicates that everything is okay. However, upon checking the database, there is nothing saved. Can ...

Sending emails with multiple attachments in PHPI'm looking

I have written this code to send multiple attachments: $file_array=$_FILES["file"]; //array of files if(!empty($file_array['name'])){///if attachment $uid = md5(uniqid(time())); $header = "From: od\n"; $header .= "M ...

Search through the directory of images and generate a JSON representation

I'm looking for a way to transform a URL-based directory of images into a Json object, which I can then utilize and connect within my Ionic project. Despite extensive searching, I have yet to find any satisfactory solutions to this challenge. Thus, I ...

Leveraging MVC 4 for Web Service Development

I am currently in the process of developing a web service using MVC 4 and HTML for the client interface. One issue I am facing is that my HTML file is located outside of the application, while my MVC service is running on Visual Studio IIS Express. I' ...

Experiencing connectivity issues with Apache Server on XAMPP

Just recently, I decided to set up the XAMPP Control Panel for my PHP project. However, I encountered an issue where it is not allowing me to connect to the Apache server. The XAMPP Control Panel keeps displaying an error message whenever I try to establis ...

Creating a universal variable in Laravel with just one word

There's something I'm not sure about, I'd like to create a variable called @ads in the view files so that whenever @ads is used, it would call a specific div element: <div class="ads"> @if(condition) some block of codes... ...

How to handle a bad request response in AJAX while reading JSON result

If the user doesn't fill out the form correctly, I want to send an error message via ajax. Here is how I send the response to the browser using ajax: if($bo){ header('HTTP/1.1 400 Bad Request'); header('Content-Type: applicati ...

"Enhance Your WordPress Website with the Power of jQuery

I have been developing a unique Wordpress plugin that incorporates a grid loading effect using jQuery. The script I have implemented is as follows: <script type="text/javascript"> new GridScrollFx( document.getElementById( 'grid' ), { ...

Working with PHP to retrieve values from an array object

I have the following array: businesscommercialArray = { 40E: { id: 94, swift_code: "40E", status: 1 }, 43P: { id: 106, swift_code: "43P", status: 2, note: "Allowed (INSTEAD OF EXIST ...

Attempting to categorize words containing 4 or more characters alongside words containing 3 or fewer characters using preg_match_all

Currently, I am attempting to categorize words with 4 or more characters together with those containing 3 or less characters using preg_match_all() in PHP. This is specifically for a keyword search feature where users can input phrases like "An elephant," ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

I am concerned about the security of my games as they can be easily hacked through right-click inspect. What measures can

As a newcomer to game development, I am creating web games using JS, HTML, and CSS. However, I have encountered an issue with preventing right-click inspect hacking, which has led to people hacking my games through this method. I am wondering, how can I s ...

What are the names of these limitations? Is there a way for me to learn more about them?

Hey there, I've been experimenting with setting up a 'custom' ACL that includes additional constraints. Typically, an ACL check looks like this: if(aclCheck($user, 'edit', 'really_important_value')){ // Allow $user t ...

The functionality of the d3 Bar chart with a tool tip seems to be malfunctioning

Working on a D3 svg chart with built-in tooltips using the d3-tip library. Check out the original code here. Utilizing Django as the back end to populate log count per year from datetime. Successfully populated axis and labels except for the bars. Here i ...

The chosen option from the drop-down menu cannot be shown on the screen

I have developed an application that you can access for testing purposes APPLICATION, but I am encountering some minor issues that I'm struggling to resolve. Despite having correct queries, the selected module is not being displayed in the code sn ...

Adjust the message hues upon form submission with Ajax

Can anyone provide assistance? I am in need of a functional form for sending emails. <form enctype="multipart/form-data" role="form" id="form" method="post" action="handler.php"> <div class="form-row"> <div class="form-g ...