0

I am very much a noob...so please go easy :)

I need to replicate this json using a php json encode:

{
  "payment": {
    "amount": 10.00,
    "memo": "Client x paid with $10.00 of nickles"
  }
}

Here is what I am doing, but it doesn't seem to work. I think it has to do with the "payment" key possibly not being represented somehow in the following code?

    $params = array(
                      'payment'     => "",
                      'amount'      => $paymentAmount,
                      'memo'        => $memo
                    );

    $content = json_encode($params);

    // send to chargify
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

2 Answers 2

1
 $params = array(
             'payment'=> array(
                           'amount'   => $paymentAmount,
                           'memo'    => $memo
                          ),
            );
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I've been beating my head against the wall for an hour. Knew it was something along these lines.
1

In general, if you know what you want the JSON to look like but don't know how to build the PHP array, just use json_decode on the well-formed JSON and examine the result:

$json = '{
          "payment": {
              "amount": 10.00,
              "memo": "Client x paid with $10.00 of nickles"
              }
        }';
$arr = json_decode($json,true);

print_r($arr);

Output:

[
    'payment' => 
    [
        'amount' => 10,
        'memo' => 'Client x paid with $10.00 of nickles',
    ],
]

Examining the output tells you how to build the array.

The same basic idea can be applied in the reverse direction if you know the array shape you need, but you're not sure what the JSON should look like. Just json_encode the good array and examine the results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.