首页 > 解决方案 > mysql select query WHERE json_contains 匹配但不返回数据?

问题描述

背景:我正准备完成一个使用贝宝订阅的项目。前端使用经过用户身份验证的 cookie,在用户同意订阅时将订阅 ID 保存到用户所属的公司。然后,当 webhook 从 paypal 进来时,我想查询公司表以查找订阅 webhook 属于哪个公司。然后我打算将 webhook 数据保存在它自己的表中,包括它所属的公司 ID。

这将允许我稍后运行通过 webhook 表的服务,并验证每个订阅是否合法,并知道订阅与哪个公司相关联。


这是查询,它需要返回找到匹配的公司的 id:

SELECT id FROM companies WHERE json_contains(paymentData->'$[*].subscriptionID', json_array("I-5TEN0ATEN0ATF"));

我的表架构如下所示:

id
name
settings
adminSettings
meta
paymentData
created
modified

我的其他不使用 json_contains 的查询没有问题,我认为这与 json_contains 有关。

当我在 PHPMyAdmin 中运行查询时,它会找到正确的行并将其显示在屏幕上,其中找到匹配项的 json 字段突出显示。看起来一切都很好,但是...

当我在我的 NodeJS API 中放置同样的查询并在 webhook 进入时执行它时,我得到一个没有数据的结果,就好像它说是的,找到了一个匹配项,但不会给你任何数据。为什么?

在这种情况下,我希望获得的公司 ID 是1. 以下是我的 API 的控制台输出,查询返回一个名为 result 的变量,它是一个包含 2 个条目的数组,第一个应该包含数据,第二个是列模式:


Full Result:  [ [],
  [ FieldPacket {
      catalog: 'def',
      db: 'test',
      table: 'companies',
      orgTable: 'companies',
      name: 'id',
      orgName: 'id',
      charsetNr: 63,
      length: 255,
      type: 3,
      flags: 16899,
      decimals: 0,
      default: undefined,
      zeroFill: false,
      protocol41: true } ] ] 

从 SQL 存储库文件中查询:

module.exports = {
  [...],
  findCompanyBySubscriptionId: 'SELECT id FROM companies WHERE json_contains(paymentData->"$[*].subscriptionID", json_array("?"))',
   [...]
};

我的 API/路由代码:


var Promise = require('bluebird');
var mailer = require('../../plugins/mailer');
var paypal = require('paypal-rest-sdk'); // Include paypal sdk

// Set your configuration object
paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': '---',
  'client_secret': '---'
});

module.exports = function (req, res) {
  let payload = req.body
  var SQLRep = req.app.locals.SQLRep; // Bring in my SQL queries
  
  req.app.locals.mysqlDB.getConnection((error, connection) => {
    return new Promise((resolve, reject) => {
      // Sends the webhook event data to PayPal to verify the webhook event signature is correct and
      // the event data came from PayPal.
      var headers = {
        'paypal-auth-algo': req.headers['paypal-auth-algo'],
        'paypal-cert-url': req.headers['paypal-cert-url'],
        'paypal-transmission-id': req.headers['paypal-transmission-id'],
        'paypal-transmission-sig': req.headers['paypal-transmission-sig'],
        'paypal-transmission-time': req.headers['paypal-transmission-time'] // style["text-align"]
      };

      console.log('payload: ', payload) // the post data coming in

      var webhookId = "1T966411BN030704L"; // hard code sample webhook ID, which does exist in the database

      return paypal.notification.webhookEvent.verify(headers, payload, webhookId, function (error, response) {
        if (error) {
          console.log('Verify error:', error, '');
          throw error;
        } else {
          if (response.verification_status === "SUCCESS") {
            resolve(response)
          } else {
            reject(response)
          }
        }
      })

    })

      .then(function (result) {

        if (result.verification_status === "SUCCESS" && payload.event_type == 'BILLING.SUBSCRIPTION.ACTIVATED') {
          // Save this webhook in the database webhooks table
          // Find a company with a matching subscription ID
          // If found, add the webhook ID to the company it belongs to
          return Promise.fromCallback(function (cb) {
            // findCompanyBySubscriptionId: 'SELECT id FROM companies WHERE JSON_EXTRACT(paymentData, "$.frontend") LIKE ?',
            return connection.query(SQLRep.findCompanyBySubscriptionId, [payload.resource.id], cb)
          }, { multiArgs: true })
            .then(function (result) {
              console.log("Full Result: ", result, '\n\n')
              return result
            })
        }
      })
      .then(() => {
        // res.status(504).send('Failed Validation'); // Let paypal this is a valid end point
        res.status(200).send('OK'); // Let paypal this is a valid end point
        console.log('sent status 200 OK\n\n--------------------------------------------------\n\n')
      })
      .finally(() => {
        connection.release();
      })
      .catch(e => {
        if (e.message == 'No Rows Returned') {
          return res.status(404).send({ 'error': e.message })
        } else if (e.message == 'invalid link or token') {
          return res.status(404).send({ 'error': e.message })
        } else if (e.message == 'invite expired') {
          return res.status(404).send({ 'error': e.message })
        } else if (e.message == 'missing required') {
          return res.status(404).send({ 'error': e.message })
        } else if (e.message) {
          return res.status(404).send({ 'error': e.message })
        }
        return res.sendStatus(500);
      })
  })
}

标签: mysqlnode.jspaypal-subscriptionsmysql-json

解决方案


推荐阅读