Mon Jun 10 2019
Copied to clipboard! Copy reply
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
const express = require("express")
const Stripe = require('stripe')
const Mailgun = require('mailgun-js')
const { Datastore } = require('@google-cloud/datastore')


const isEmail = require('validator/lib/isEmail')
const isLength = require('validator/lib/isLength')
const cors = require('cors')
const app = express()
const ds = new Datastore( { productId: 'bnbcrate1' })


// Only needed in dev, GCF already includes for you
var bodyParser = require('body-parser')
app.use(bodyParser.json())

app.use(cors())
app.listen(8080);


/**
 * By default, load prod values.
 */
var mailgunKey = '779a6a20423f010b0d9cfc76e177e5f6'
var stripeKey = 'sk_live_bQhKekL9Rzt6IPkN217YKlVu'

/**
 * For any route, determine if we are in dev or prod environment
 */
app.use(function(req, res, next) {
  req.environment = req.headers['x-environment'] == 'prod' ? 'prod' : 'dev'
    
  if (req.environment == 'dev') {
    stripeKey = 'sk_test_bypTtufI6HZA4YpaLBWLMEZX'
    mailgunKey = '779a6a20423f010b0d9cfc76e177e5f6'
  } 
  next()
})


/**
 * Define products:: TODO should actually be a bucket file
 */
const products = [
  {
    id: 1,
    name: "Basic",
    price: 6.99,
    items: [ "1 Shampoo", "1 Conditioner", "1 Soap", "1 Shower Cap" ]      
  },
  {
    id: 5,
    name: "Premium",
    price: 14.99,
    items: ["1 Shampoo", "1 Conditioner", "1 Soap", "1 Shower Cap", "2 Toothbrushes", "2 Toothpastes", "2 Towels"]
  }
]  



/**
 * Route to return our products
 */
app.get('/products', (req, res, next) => {
  res.status(200).json(products);
})


/**
 * Route checks user's cart out.
 */
app.post('/checkout', async (req, res, next) => {
  
  

  console.log('--- body')
  console.log(req.body)
  // Holds order's data, such as email, shipping info, products...
  const data = req.body.orderData || null

  // JWT token lets us know if user is logged in
  const jwtToken = req.body.jwt || null

  // Strike Token that is passed if paying with a new credit card
  const stripeToken = req.body.stripeToken || null
  
  // Stripe (customer) ID and card ID are sent if user is paying with a stored credit card   
  const stripeId = req.body.stripeId || null
  const cardId = req.body.cardId || null

  // Total amount of purchase
  let serverTotal = 0


  const stripe = Stripe(stripeKey)
  const emailDomain = 'mail.bnbcrate.com'
  const mailgun = Mailgun({ apiKey: mailgunKey, domain: emailDomain })

  var userId = null
    
  if (jwtToken)
  {
    let decoded= jwt.verify(jwtToken, process.env.JWT);
    userId = decoded.id      
  }   
    
  var invalidData = false   

    
  if (!stripeToken)
  {      
    if (!stripeId || !cardId)
    {
      invalidData = true
    }
  }

  if (!stripeId && cardId)
  {
    if (!stripeToken)
    {
      invalidData = true
    }
  }

  if (!data.crates.length)
  {
    invalidData = true
  }

  if (invalidData)
  {
    // TODO log
    return res.json({
      result: 0,
      payload: { 
        message: 'Something went wrong. Data is missing. Please reload the page and try again.'
      }
    })    
  }

  
  /**
   *
   * Client Sends: [ { id: 1, quantity: 2, price: 5.99} ]
   * We need to make sure that the ID of each crate sent by client
   * exists in the server, and that the price for that crate sent by
   * the client also matches the server. So if client sends a crate
   * of id 1 where price is $6, we need to make sure server has a crate
   * of id 1 and that its price is $6     
   */    
  
  // const clientTotal = data.crates
  //   .map(e => e.price * e.quantity)
  //   .reduce((acc,cv) => acc + cv)   
  for (let crate of data.crates)
  {
    let clientId = crate.id
    let clientPrice = crate.price    
    
    // Check if ID exists in the products "database"
    let [ serverCrate ]  = products.filter(c => c.id == clientId) || null

    // The crate id sent from client does not exist in the server.
    if (!serverCrate || clientPrice != serverCrate.price)
    {
      // TODO log
      return res.json({
        result: 0,
        payload: { 
          message: 'Product mismatch. Please try again' 
        }
      })    
    }
    else
    {
      // Gets passed to stripe
      serverTotal += serverCrate.price
    }
  }
     
    
  // Sanitize the data sent    
  if (!sanitizeInputs(data))
  {
    // TODO log
    return res.json({
      result: 0,
      payload: { 
        message: 'Bad input.' 
      }
    })     
  }

  // Validation passed.
  let email = data.email.toLowerCase()    

  // Not needed..just wasting datastore space
  delete data.shipping['id']  
      
  var charge = null
    
  try
  {
    const stripeData = {
      amount : (serverTotal * 100), // Stripe wants cents.
      currency : 'usd',
      description : `Charge for ${email}`,
      metadata: {          
        dsUserId: '',
        items: '',
        email: email,
        name: data.shipping.name,
        street: data.shipping.street,
        city: data.shipping.city,
        state: data.shipping.state,
        zip: data.shipping.zip,          
      }
    }

    if (stripeToken)
    {
      // New credit card
      stripeData.source = stripeToken.id
    }
    else
    {
      // Applying a saved credit card to a customer
      stripeData.source = cardId
      stripeData.customer = stripeId
    }

    
    charge = await stripe.charges.create(stripeData)

    // Now save in the datastore
    let datastoreOrder = await saveOrderInDB({
      email: email,
      userId: userId,
      items: data.crates,
      shippingAddress: data.shipping,
      currency: 'usd',
      guest: data.guest,
      total: serverTotal
    }, charge.id)

    // Now send email
    /*
    let templateUri = `${__dirname}/../email-templates/order-confirmation.html`
    let emailTemplate = readFileSync(templateUri, 'utf-8')
    let compiled = template(emailTemplate)
    let emaildata = {
      from: `bnbcrate <orders@${emailDomain}>`,
      to: email,
      subject: 'Your bnbcrate order',
      html: compiled({
        crates: data.crates,
        address: data.shippingAddress,
        orderId: datastoreOrder.payload.key.id 
      })
    } 

    mailgun.messages().send(emaildata, (e, body) => {
      if (e)
      {        
        // TODO log
      }        
    })
    */


    res.json({ result: 1 })
  }
  catch (e)
  {     
    console.log(e)
    // TODO log
    return res.json({
      result: 0,
      payload: { 
        message: 'Could not charge card. Please try again' 
      }
    })  
  }




});







  /**
   * Sanitizes all user inputs from the client.
   * Best way to know all the inputs is to take
   * a look at the client store.
   *
   * @param {Object} data: ctx.request.body
   */
  function sanitizeInputs(data)
  {
    const email = data.email
    //const crates = data.crates
    const shipping = data.shipping
    
    var error = []    
    
    if (!isEmail(email))
    {
      error.push('Invalid email.')
    }

    // Shipping Fields
    if (!isLength(shipping.street, {min: 1}))
    {
      error.push('Invalid shipping address.')
    }

    if (!isLength(shipping.zip, {min: 3}))
    {
      error.push('Invalid shipping zip code.')
    }

    if (!isLength(shipping.country, {min: 2, max: 2}) || shipping.country != 'us')
    {
      error.push('Invalid shipping country.')
    }  

    
    if (error.length)
    {
      return false
    }
    return true

  }


  /**
   * Saves an order into the datastore.
   * 
   * @param {String} email - buyer's email
   * @param {Int} userId - user's id, if logged in
   * @param {String} chargeId - charge ID generated by Stripe
   * @param {String} shippingAddress - shipping address
   * @param {Object} items - Items being purchased {crate: qty}
   * @param {Int} total - total price charged
   * @param {String} currency - charge currency
   * @param {String} paymentMethod - payment method. cc or paypal
   * @param {Date} date - date and time
   * @param {String} status - order status. 'new' by default
   * @param {String|int} dsId - unique ID for datastore's key. (order's ID)
   */
  function saveOrderInDB(data, dsId)
  { 
    const orderEntity = {
      key: ds.key(['Order', dsId]),
      data: [
        {
          name: 'email',
          value: data.email
        },
        {
          name: 'userId',
          value: data.userId || null
        },        
        {
          name: 'shippingAddress',
          value: data.shippingAddress,
          excludeFromIndexes: true
        },
        {
          name: 'items',
          value: data.items,
          excludeFromIndexes: true,
        },
        {
          name: 'total',
          value: data.total,
          excludeFromIndexes: true
        },
        {
          name: 'currency',
          value: 'usd',
          excludeFromIndexes: true
        },
        {
          name: 'guest',
          value: data.guest || null
        },
        {
          name: 'paymentMethod',
          value: 'credit card'
        },
        {
          name: 'date',
          value: new Date()
        },
        {
          name: 'status',
          value: 'new'
        },
        {
          name: 'dateShipped',
          value: null
        }
      ]
    }
    
    return ds.insert(orderEntity)
      .then(result => { 
        
        // We return the order entity so we can use it to update
        return { result: 1, payload: orderEntity }
      })
      .catch(e => {        
        // TODO log
        console.log(e)
        return {
          result: 0,
          payload: {
            message: `Could not save order. Please try again. ${e}`
          }
        }
      })
    
    
  }





module.exports = {
  checkout: app
}

// Server makes a GC functions api call to fetch products - since it's internal, cant be intefered