读取数据发布到钩子

时间:2017-08-21 19:08:01

标签: php

我有一个php函数,可以从Web服务接收数据。我已将该功能设置为我的数据接收器

发布到我的钩子的数据看起来像这样

service_name=M-PESA&business_number=896747&transaction_reference=LHL8XS8N1K&internal_transaction_id=7874122&transaction_timestamp=2017-08-21T18%3A42%3A17Z&transaction_type=buygoods&account_number=N%2FA&sender_phone=%2B254720069005&first_name=RON&middle_name=&last_name=AVERY&amount=2.0&currency=Ksh&signature=Z5RI5VtwyI9T2xHgI2GVW8LmnIw%3D&username=very%40gmail.com&password=droid2090

我的代码看起来像这样

public function webhook()
    {
    $post_content = file_get_contents("php://input");

    $webhook = json_decode($post_content);
    $amount = $webhook["amount"];
    $telephone = $webhook["sender_phone"];
    $code = $webhook["transaction_reference"];
    $date_updated = time();
    $id = rand(3,1000);
    $status = 'unseen';

    $data = array(
    'id' => $id,
   'amount' => $amount,
   'telephone' => $telephone,
   'code' => $code,
   'date_updated' => $date_updated,
   'status' => $status
   );

   $this->db->insert('dbo.mpesa', $data);
    }

出于某种原因,我无法使用下面的代码获取数据,尽管我可以看到Web服务已到达钩子,因为它将null插入数据库。

我是否错误地发布了数据?

1 个答案:

答案 0 :(得分:0)

JSON不会被发布回您的网络服务...所以json_decode将返回null。

您最有可能希望使用parse_str()

  

void parse_str(string $ encoded_string [,array& $ result])

     

解析encode_string,就好像它是通过URL传递的查询字符串一样   并在当前范围内设置变量(如果结果为,则设置在数组中)   提供)。

利用第二个参数,将数据作为数组放入$webhook变量中:

$post_content = file_get_contents("php://input");

parse_str($post_content, $webhook);

-

旁注:

您不会想要设置'id' => $id,因为这会在3,1000 ID池中随机中断(假设这是一个自动增量ID)。