You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.3 KiB
Lua

local cjson = require "cjson"
local redis = require "redis"
local global = require "global"
local keysutils = require "keysutils"
local genid = require "genid"
local jwt = require "resty.jwt"
local resty_md5 = require "resty.md5"
local str = require "resty.string"
local http = require "http"
local wechat = require "wechat"
local resty_sha1 = require "resty.sha1"
local function sha1(str)
local sha1 = resty_sha1:new()
sha1:update(str)
return sha1:final()
end
-- 将二进制摘要转化为十六进制字符串
local function to_hex(digest)
return string.gsub(digest, ".", function(c)
return string.format("%02x", string.byte(c))
end)
end
local arg=ngx.req.get_uri_args()
ngx.header['Content-Type'] = 'application/json; charset=utf-8'
local body = ngx.req.get_body_data()
ngx.log(ngx.INFO,"body=======================>",body)
local ok, req_data = pcall(cjson.decode,body)
if not ok then
return ngx.say(cjson.encode({errcode=10000, errmsg="系统繁忙", data={}}))
end
local url = req_data.url
if not url then
return ngx.say(cjson.encode({errcode=10001, errmsg="参数错误", data={}}))
end
local rediscli = redis:new(global.get_redis_conf())
local k = string.format("%s:wechat:ticket", tostring(global.get_appname()))
local ticket = rediscli:get(k)
if not ticket then
local token = wechat.getAccessToken()
local req_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="..token;
local resp_str = http.get(req_url)
local ok, resp = pcall(cjson.decode, resp_str)
if not ok then
return ngx.say(cjson.encode({errcode=10001,errmsg="票据获取失败",data={}}))
end
if resp.errcode and resp.errcode == 0 then
ticket = resp.ticket
rediscli:set(k, ticket, "ex", expires_in)
else
return ngx.say(cjson.encode({errcode=10002,errmsg="票据获取失败",data={}}))
end
end
local nonceStr = genid.gentoken(32)
local timestamp = tostring(os.time())
local sign_str = "jsapi_ticket="..ticket.."&noncestr="..nonceStr.."&timestamp="..timestamp.."&url="..url
local digest = sha1(sign_str)
local signature = to_hex(digest)
local resp = {
nonceStr=nonceStr,
timestamp=timestamp,
signature=signature,
}
ngx.say(cjson.encode({errcode=0,errmsg="",data={data=resp}}))