2017-09-04 121 views
0

我正在查看我的代碼和我的結果,但沒有看到任何明顯的錯誤,所以我認爲可能有一些額外的眼睛看起來很有用結束了。WordPress中的奇怪行爲MySQL插入JSON編碼數據

我有一個自定義的PayPal IPN偵聽器,用於更新數據庫中的事務表。我在離開工作前的星期五部署了它,今天返回後,它似乎正常工作主要是;但我想弄清楚爲什麼一個插入行爲奇怪。

下面是其中發生在上週末的插入的捕捉: PayPal IPN log

正如你可以看到,第四屆交易log列預期JSON值爲空。我覺得很奇怪,因爲transaction_id列的值是從同一個數組中解析出來的。

下面是相關數據庫insert代碼:

// Generate valid IPN log 
private function generateIpnLog() { 
    global $wpdb; 

    // prepare log 
    $array_log = []; 
    $array_log['verified'] = true; 
    $array_log['ipn_response'] = (isset($this->PayPal_Response)) ? : 'Error reading from POST array'; 

    // Parse transaction ID 
    $transaction_id = (isset($this->PayPal_Response['txn_id'])) ? $this->PayPal_Response['txn_id'] : null; 

    // Generate log 
    $log = json_encode($array_log); 

    // Update DB 
    $wpdb->insert(
     'log_paypal', 
     [ 
      'transaction_id' => ($transaction_id) ? $transaction_id : 'Error getting transaction ID', 
      'log' => ($log) ? $log : 'Error generating transaction log' 
     ], 
     [ 
      '%s', 
      '%s' 
     ] 
    ); 

    // json log response 
    $this->json_return = $log; 
} 

看到,因爲事務ID解析罰款從PayPal的反應,因爲我們知道$array_log['verified']有一個顯式聲明價值我的猜測是,必須有一個問題與json_encode($array_log)

我還檢查了貝寶IPN歷史記錄中有關PayPal賬戶的數據,並且可以驗證數據在空值log列與其他列中形成的方式沒有任何不同。

任何人都知道在這種情況下會發生什麼?

+0

如果我這樣做是正確,你可以看到'log'('$ array_log')應該在空行中?你應該編輯它,它非常相關。 – ishegg

+0

@ishegg我不確定你的問題是什麼,但如果你問我是否可以用IPN數據手動更新該行 - 是的,我可以,而且已經有了。但從長遠來看,這顯然沒有幫助。 – DrewT

+1

不,我的意思是,你可以手動重建'$ array_log',看看它爲什麼沒有正確編碼? – ishegg

回答

0

正如@ishegg所示,這是一個編碼問題,因爲PayPal IPN使用windows-1252編碼並且DB字段編碼爲UTF-8

在這種情況下很容易修復,因爲PayPal返回數據不是嵌套的/多維的(見下文)。

// Process IPN response 
$this->PayPal_Response = $this->processIpn(); 

然後,函數本身:

在PayPal的IPN入境後的早期功能堪稱是加密由證書鏈覈實

// Manipulate IPN response and prepare 
// for database update and log 
private function processIpn() { 
    // Response ref. 
    $response = $this->post_array; 

    if (isset($response['charset'])) { 
     if ($response['charset'] == "windows-1252") { 
      foreach ($response as $key => $ipn_value) { 
       $response[$key] = mb_convert_encoding($ipn_value, 'UTF-8', 'Windows-1252'); 
      } 
     } 
    } 
    return $response; 
}