Nginx Order

Eave 2017.04.19 17:37
server
{
    listen       80;
    server_name  lua.htc.com;

    root   /var/www/vhosts/www;
    index  index.html index.htm index.php;

    access_log  /var/log/nginx/lua.htc.com.log  access;
    error_log   /var/log/nginx/error.log notice;

    charset utf-8;
    lua_code_cache on;

    location /order/create
    {
        content_by_lua_file '/usr/local/nginx/conf/lua/outTradeNo.lua';
    }
}
#!/usr/bin/lua

local os = require("os")
local time = os.time();
local redis = require("resty.redis")
local cjson = require("cjson")

local key = "NginxIncr"
local host = "127.0.0.1"
local port = 6379

-- 连接redis
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect(host, port)
if not ok then
    return
end

-- 返回一个唯一的订单号
function outTradeNo()
    local id, err = red:incr(key)
    -- Redis设置过期时间
    if id == 1 then
        -- 将时间转为时间戳
        local date = os.date("*t", time + 3600)
        -- 计算Key的过期时间
        local expire = os.time({year=date.year, month=date.month, day=date.day, hour=date.hour, minute=0, second=0}) - time
        red:expire(key, expire)
    end

    return string.format("%03x", 520) .. string.format("%03x", 1120) .. os.date("%y%m%d%H") .. string.format("%05d", id)
end

-- 获取POST参数
ngx.req.read_body()
local args = ngx.req.get_post_args()

local out_trade_no = outTradeNo()
local total_fee = args["total_fee"]
if total_fee == nil then
    total_fee = 0.01
else
    total_fee = tonumber(total_fee)
end

local subject = args["subject"]
if subject == nil then
    subject = "订单"
else
    subject = subject
end

-- 获取请求头信息
local header = ngx.req.get_headers()

local data = {}
data["create_time"] = os.time()
data["ip"] = ngx.var.remote_addr
data["out_trade_no"] = out_trade_no
data["total_fee"] = total_fee
data["subject"] = subject
data["status"] = 1
data["pay_type"] = 1
data["refund_amount"] = 0
data["pay_time"] = 0
data["user_agent"] = header["User-Agent"]

local resp = {}
resp["errcode"] = 0
resp["errmsg"] = "success"
resp["data"] = data

local orderkey = "OrderHash"
local ok, err = red:rpush(orderkey, cjson.encode(data))

-- 设置响应头信息
ngx.header["Content-Type"] = "application/json;charset=UTF-8"
ngx.header["X-User"] = "QianYan"
ngx.header["X-Powered-By"] = _VERSION -- 获取Lua版本号
-- 内容输出
ngx.say(cjson.encode(resp))
-- 设置响应状态码
ngx.exit(ngx.HTTP_OK)