1. 程式人生 > >openresty 前端開發進階二之https後端

openresty 前端開發進階二之https後端

在對接一些第三方系統的時候,經常會遇到https的問題,好比如做微信公眾號的開發,介面基本都是https的,這個時候,很多人試著用http的那種方式來訪問https,結果報錯了,誤以為lua不支援https,其實不是的,只需要配置一個證書即可,證書可以通過瀏覽器訪問介面的url,然後通過瀏覽器匯出這個網站所對應的pem證書,然後配置到nginx裡面就行了,其他的呼叫方法跟http的型別,所用到的http庫,跟我寫的這篇文章一致,就不過多介紹了

nginx.conf


worker_processes  1;

error_log logs/error.log notice;

events
{ worker_connections 1024; } http { lua_ssl_verify_depth 2; lua_ssl_trusted_certificate GeoTrust_Global_CA.pem; lua_package_path "$prefix/lua/?.lua;$prefix/lualib/?.lua"; server { listen 8888; server_name localhost; lua_code_cache off; location / { root
html; index index.html; } location ~ /lua/(.+) { default_type text/html; resolver 223.5.5.5 223.6.6.6; # 這裡位設定阿里的DNS,不設定DNS無法解析http請求的域名 content_by_lua_file lua/$1.lua; } } }

為了簡單起見,以下只是調一下獲取access_key的介面,只要這個可以,同理,微信下單那些也是一樣的,這點可以保證,我就用openresty做過微信公眾號開發,包含微信登入,微信支付,以及資料庫mysql部分全都是lua開發的

lua/test.lua

local req = require "req"
local cjson = require "cjson"
local http = require "resty.http"

function get_access_token(code)
    local httpc = http.new()
    local params = {}
    params['grant_type'] = 'authorization_code'
    params['appid'] = '' -- config.appid
    params['secret'] = '' -- config.secret
    params['code'] = ''
    local res,err = httpc:request_uri("https://api.weixin.qq.com/sns/oauth2/access_token?" .. ngx.encode_args(params), {
        method = "GET",
        headers = {
            ["Accept"] = "application/json",
            ["Accept-Encoding"] = "utf-8",
        }
    })
    print(err)
    httpc:set_keepalive(60)
    return cjson.decode(res.body)
end

local args = req.getArgs()
local code = args['code']
local res = get_access_token(code)
ngx.say(cjson.encode(res))
ngx.say(res.openid)

index.html

<html>
<head>
    <meta charset="UTF-8">
    <title>Login Page</title>
</head>
<body>
    <a href="javascript:void(0)" onclick="test()">測試</a>
    <pre id="ret"></pre>
    <script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <script>
        function test() {
            $('#ret').load('/lua/test', {code: '123456'})
        }
    </script>
</body>
</html>

啟動nginx

$ openresty -p `pwd`/demo13

應該會返回類似以下這樣的東西,說明呼叫成功了,只是引數有問題而已

{"errcode":41002,"errmsg":"appid missing, hints: [ req_id: eMR_KA0444ns88 ]"}
nil

到此,你可以用openresty更深層次的跟後端進行整合,開發出更強大的前端應用了,當前開發方式很簡單,部署也只需要一個nginx

示例程式碼 參見demo13部分