由于要实现公众号的各种功能首先是要获取access_token,这个access_token并不是最初填写服务器的token,而是需要appid和secret去微信服务器申请的。
其次就是OpenResty本身要发起http请求是一件比较麻烦的事情,还好有春哥写了个lua_resty_http,让Openresty发起http请求更容易。我使用的是其中一个分支:https://github.com/pintsized/lua-resty-http
下载之后用scp放到服务器上(直接在服务器上wget也不是不可以),我存放的路径是: /usr/local/openresty/lualib/resty,接着在nginx.conf中添加lua文件的路径:lua_package_path "/usr/local/openresty/lualib/resty/lua-resty-http/lib/?.lua;;";
另外再添加一个location:
location /ask_accesstoken {
content_by_lua_file /path/to/ask_accesstoken.lua;
}
接下来就是干货了:
local http = require "resty.http"
local httpc = http:new()
local res, err = httpc:request_uri("https://api.weixin.qq.com/cgi-bin/token", {
method = "GET",
query = {
grant_type = "client_credential",
appid = "APPID", --填写自己的appid
secret = "SECRET", -- 填写自己的secret
},
ssl_verify = false, -- 需要关闭这项才能发起https请求
headers = {["Content-Type"] = "application/x-www-form-urlencoded" },
})
if not res then
ngx.say("failed to request: ", err)
return
end
ngx.status = res.status
ngx.say(res.body)
编辑完毕后,试验后,可能还会发生一个问题:failed to request: api.weixin.qq.com could not be resolved (110: Operation timed out)。
这是因为需要DNS解析,此时再在nginx.conf的server中添加一句:resolver 114.114.114.114;(这个是公共的DNS解析服务器地址,我用google的8.8.8.8有时候会访问不了,得益于某堵墙 = =)。
这样折腾后就能够获取access_token了,妥妥哒。
本文介绍如何使用OpenResty发起HTTP请求以获取微信公众号的access_token,并解决过程中遇到的DNS解析问题。
1198

被折叠的 条评论
为什么被折叠?



