local cjson = require "cjson" local http = require "resty.http" local pl = require "pl.pretty" local httpc = http.new() local sudoerToken = ngx.req.get_headers().HtySudoerToken local htyhostHeader = ngx.req.get_headers().HtyHost local function get_access_token() local htyuc = ngx.var.htyuc local host = ngx.var.host local wx_domain = ngx.var.wx_domain ngx.log(ngx.INFO, "HTYUC -> ", htyuc) ngx.log(ngx.INFO, "Host -> ", host) ngx.log(ngx.INFO, 'HtyHostHeader -> ', htyhostHeader) ngx.log(ngx.INFO, 'HtySudoerToken -> ', sudoerToken) local remote_url = string.format("%s/api/v1/uc/wx_get_access_token", htyuc) ngx.log(ngx.INFO, 'REMOTE URL -> ', remote_url) ngx.log(ngx.INFO, "START REQUEST TO GET ACCESS TOKEN -> ", pl.write(sudoerToken)) local no_exception, resp, resp_err = pcall(httpc.request_uri, httpc, remote_url, { ssl_verify = false, -- 设置参数 ssl_verify 为false 不校验ssl证书 --pool = nil, --pool_size = nil, method = "GET", headers = { ["HtyHost"] = wx_domain, ["HtySudoerToken"] = sudoerToken, } }) ngx.log(ngx.INFO, "RESP -> ", pl.write(resp)) httpc:close() if no_exception == true then if 200 ~= resp.status then ngx.log(ngx.ERR, "GET ACCESS TOKEN *FAILED*", pl.write(resp_err)) ngx.status = resp.status ngx.say(pl.write(resp_err)) --httpc:close() ngx.exit(resp.status) else ngx.log(ngx.ERR, "RESP IS OK -> ", pl.write(resp.body)) --httpc:close() return cjson.decode(resp.body).d end else if resp == nil then resp = "" end ngx.log(ngx.ERR, "FAILED TO CONNECT TO *HTYUC*: httpc throws runtime error, please check HTYUC log. / ", pl.write(resp)) -- 必须先设置ngx.status,否则ngx.say之后就直接被设置为200了,不会再被exit设为401 -- https://github.com/openresty/lua-resty-redis/issues/15 ngx.status = 401 ngx.say(cjson.encode({r = false, d = "HtySudoerTokenErr"})) --httpc:close() ngx.exit(401) end end local function get_wx_media(media_id) local access_token = get_access_token() print("access token: " .. access_token) local wx_media_url = string.format("https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s", access_token, media_id) print("wx_media_url: " .. wx_media_url) local resp, req_err = httpc:request_uri(wx_media_url, { method = 'GET', ssl_verify = ssl_verify or false, -- 设置参数 ssl_verify 为false 不校验ssl证书 }) if resp == nil then ngx.log(ngx.ERR, "FAILED TO CONNECT TO *Weixin*", req_err) ngx.status = 500 ngx.say(req_err) ngx.exit(500) end if 200 ~= resp.status then ngx.log(ngx.ERR, 'GET WECHET MEDIA *FAILED*', req_err) ngx.status = resp.status ngx.say(req_err) ngx.exit(resp.status) end local filename = ngx.re.match(resp.headers['Content-disposition'], [[filename="(.+\.([a-zA-Z0-9]+))"]], "jo")[1] local file_dir = ngx.var.tmp_file_dir local saved_file = file_dir .. "/" .. filename; print('saved file...' .. saved_file); local file, err = io.open(saved_file, 'w') if file == nil then print("Can not open file..." .. err) else file:write(resp.body) file:close() end return saved_file, filename; end return get_wx_media;