[英]Strange behaviour in WordPress MySQL insert of JSON encoded data
我正在查看我的代碼和結果,但沒有看到任何明顯的錯誤,因此我認為多看一些眼睛可能會很有用。
我有一個自定義的PayPal IPN偵聽器,用於更新數據庫中的事務表。 我在下班前於星期五部署了它,今天返回后,它似乎基本上可以正常工作。 但我想弄清楚為什么一個插入的行為異常。
如您所見,第四筆交易的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;
}
看到從PayPal響應中可以很好地解析交易ID,並且因為我們知道$array_log['verified']
具有$array_log['verified']
聲明的值,所以我猜想json_encode($array_log)
必須存在問題。
我還檢查了有問題的PayPal帳戶的PayPal IPN歷史記錄中的數據,並且可以驗證在null log
列中形成數據的方式與其他方式沒有什么不同。
任何人都知道在這種情況下會發生什么?
正如@ishegg所建議的那樣,這是一個編碼問題,因為PayPal IPN使用windows-1252
編碼,並且DB字段使用UTF-8
編碼。
在這種情況下,由於PayPal返回數據不是嵌套的/多維的(參見下文),因此很容易修復。
通過證書鏈對PayPal IPN條目進行加密驗證后,在較早的函數中調用:
// Process IPN response
$this->PayPal_Response = $this->processIpn();
然后,函數本身:
// 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.