OpenResty获取微信公众号access_token

本文介绍如何使用OpenResty发起HTTP请求以获取微信公众号的access_token,并解决过程中遇到的DNS解析问题。

    由于要实现公众号的各种功能首先是要获取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了,妥妥哒。

    

转载于:https://my.oschina.net/chrisforbt/blog/639560

{"log":{"version":"1.2","creator":{"name":"Reqable","version":"2.30.3"},"entries":[{"startedDateTime":"2025-05-20T07:18:39.857Z","time":43,"request":{"method":"GET","url":"https://www.gy0.cc/consumer/sc/api/getScanInfo?key=2524544%2520-T3J2ZHIO8EAE2EJJ%253AL85&pagePath=%2523%252Fsc%252FpureRawDoll%253Fkey%253D2524544%252B-T3J2ZHIO8EAE2EJJ%253AL85%2526SHUYUN_TOKEN%253D026372DD7587FCE040CD6067F9A40B1C527B233645D296A7B84D66206FCB3F5D7D66F51061A0AB6541257AA958C4D9E996BA8AFC0226ED1F8F19B5E7B1F9430AC6895F620BD86071B7C223107D25A02FCB3E1831258F80550B1027CCF727A67D%2526longitude%253D104.06688503689236%2526latitude%253D30.57524875217014","httpVersion":"HTTP/2.0","cookies":[],"headers":[{"name":":authority","value":"www.gy0.cc"},{"name":":method","value":"GET"},{"name":":path","value":"/consumer/sc/api/getScanInfo?key=2524544%2520-T3J2ZHIO8EAE2EJJ%253AL85&pagePath=%2523%252Fsc%252FpureRawDoll%253Fkey%253D2524544%252B-T3J2ZHIO8EAE2EJJ%253AL85%2526SHUYUN_TOKEN%253D026372DD7587FCE040CD6067F9A40B1C527B233645D296A7B84D66206FCB3F5D7D66F51061A0AB6541257AA958C4D9E996BA8AFC0226ED1F8F19B5E7B1F9430AC6895F620BD86071B7C223107D25A02FCB3E1831258F80550B1027CCF727A67D%2526longitude%253D104.06688503689236%2526latitude%253D30.57524875217014"},{"name":":scheme","value":"https"},{"name":"shuyun_token","value":"026372DD7587FCE040CD6067F9A40B1C527B233645D296A7B84D66206FCB3F5D7D66F51061A0AB6541257AA958C4D9E996BA8AFC0226ED1F8F19B5E7B1F9430AC6895F620BD86071B7C223107D25A02FCB3E1831258F80550B1027CCF727A67D"},{"name":"sec-ch-ua-platform","value":"\"Android\""},{"name":"user-agent","value":"Mozilla/5.0 (Linux; Android 10; Redmi K20 Pro Build/QKQ1.190825.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.136 Mobile Safari/537.36 XWEB/1340095 MMWEBSDK/20250201 MMWEBID/2949 MicroMessenger/8.0.58.2841(0x28003A3E) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64"},{"name":"accept","value":"application/json, text/plain, */*"},{"name":"sec-ch-ua","value":"\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Android WebView\";v=\"134\""},{"name":"sec-ch-ua-mobile","value":"?1"},{"name":"x-requested-with","value":"com.tencent.mm"},{"name":"sec-fetch-site","value":"same-origin"},{"name":"sec-fetch-mode","value":"cors"},{"name":"sec-fetch-dest","value":"empty"},{"name":"referer","value":"https://www.gy0.cc/consumer/sc/"},{"name":"accept-encoding","value":"gzip, deflate, br, zstd"},{"name":"accept-language","value":"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"},{"name":"priority","value":"u=1, i"}],"queryString":[{"name":"key","value":"2524544%20-T3J2ZHIO8EAE2EJJ%3AL85"},{"name":"pagePath","value":"%23%2Fsc%2FpureRawDoll%3Fkey%3D2524544%2B-T3J2ZHIO8EAE2EJJ%3AL85%26SHUYUN_TOKEN%3D026372DD7587FCE040CD6067F9A40B1C527B233645D296A7B84D66206FCB3F5D7D66F51061A0AB6541257AA958C4D9E996BA8AFC0226ED1F8F19B5E7B1F9430AC6895F620BD86071B7C223107D25A02FCB3E1831258F80550B1027CCF727A67D%26longitude%3D104.06688503689236%26latitude%3D30.57524875217014"}],"headersSize":1476,"bodySize":0,"_status":"completed","_startTimestamp":1747725519857796,"_endTimestamp":1747725519860535},"response":{"status":200,"statusText":"","httpVersion":"HTTP/2.0","cookies":[],"headers":[{"name":":status","value":"200"},{"name":"server","value":"openresty"},{"name":"date","value":"Tue, 20 May 2025 07:18:39 GMT"},{"name":"content-type","value":"application/json"},{"name":"access-control-allow-credentials","value":"true"},{"name":"access-control-allow-methods","value":"GET, POST, OPTIONS"},{"name":"access-control-allow-headers","value":"DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type"}],"content":{"size":1538,"mimeType":"application/json","text":"{\"returnCode\":\"1\",\"returnMsg\":\"获取成功\",\"errorCode\":null,\"errorCodeDes\":null,\"datas\":\"{\\\"activityRuleId\\\":10000,\\\"adCode\\\":\\\"510107\\\",\\\"appletScan\\\":true,\\\"areaHeaderUrl\\\":\\\"https://www.gy0.cc/cpmdp/sc\\\",\\\"code\\\":\\\"-T3J2ZHIO8EAE2EJJ:L85\\\",\\\"codeStoreId\\\":66605240,\\\"customerPrizeKey\\\":\\\"2524544+-T3J2ZHIO8EAE2EJJ:L85\\\",\\\"dealer\\\":{\\\"areaFirstCode\\\":\\\"50025920\\\",\\\"areaFirstId\\\":510,\\\"areaFirstName\\\":\\\"乐山销售大区\\\",\\\"areaSecondId\\\":520,\\\"areaSecondName\\\":\\\"犍为业务部\\\",\\\"areaThreeId\\\":522,\\\"areaThreeName\\\":\\\"乐山五通桥\\\",\\\"marketCenterCode\\\":\\\"50002083\\\",\\\"marketingCenter\\\":\\\"sc\\\",\\\"name\\\":\\\"乐山市五通桥区吉鸿商行\\\",\\\"no\\\":\\\"160007278\\\",\\\"waiterMaxAmount\\\":0},\\\"fillUserInfo\\\":0,\\\"member\\\":{\\\"gmtRegist\\\":1747725497730,\\\"hasUser\\\":1,\\\"headImgUrl\\\":\\\"https://thirdwx.qlogo.cn/mmopen/vi_32/kCoOHhj27ko0xKXiabIqvqpNdzMgnGfnlU3fuBftiaaqrLpic5X7ibPW1BpqqhMxA47KIRssmH3Zc0ia9HfgsYLNicjg/132\\\",\\\"id\\\":2524544,\\\"idCardNo\\\":\\\"\\\",\\\"isException\\\":0,\\\"isFocusWeixin\\\":0,\\\"mobile\\\":\\\"17705821447\\\",\\\"nickName\\\":\\\"开心就好\\\",\\\"sex\\\":\\\"0\\\",\\\"status\\\":\\\"O\\\",\\\"type\\\":\\\"XF\\\",\\\"unionId\\\":\\\"oQdqpwKgoDoZnJUvyHkR_JzYU4vg\\\"},\\\"openId\\\":\\\"od4Kx6seH0c9VMOczGCi1AeMNmhs\\\",\\\"redRain\\\":false,\\\"result\\\":[{\\\"activityType\\\":0,\\\"awardName\\\":\\\"10.8元红包\\\",\\\"count\\\":1080,\\\"drinkGame\\\":0,\\\"fillUserInfo\\\":0,\\\"rewardType\\\":4,\\\"showImg\\\":\\\"\\\",\\\"userInfoType\\\":0}],\\\"ruleId\\\":10155,\\\"showAd\\\":false,\\\"staticRoot\\\":\\\"https://www.gy0.cc/cpmdp/static/sc\\\",\\\"userInfoType\\\":0,\\\"virtualProductId\\\":148338,\\\"winBeerSquare\\\":false}\"}"},"redirectURL":"","headersSize":326,"bodySize":1538,"_status":"completed","_startTimestamp":1747725519898801,"_endTimestamp":1747725519900708},"cache":{},"timings":{"send":-1,"wait":-1,"receive":-1},"serverIPAddress":"134.175.212.211","connection":"53","comment":"","_id":159,"_uid":"2618f643-4511-42dd-87e7-986a5d204ff3","_cid":53,"_ctime":1747725516423,"_sid":81,"_stime":1747725519857,"_serverAddress":"134.175.212.211","_serverAddressFamily":0,"_serverPort":443,"_clientAddress":"192.168.51.9","_clientAddressFamily":0,"_clientPort":41844,"_app":{"name":"微信","id":"com.tencent.mm","path":null,"stackTrace":null}}]}} 帮我改成一个正常的请求
05-22
lua entry thread aborted: runtime error: content_by_lua(nginx.conf:61):16: module 'resty.http' not found: no field package.preload['resty.http'] no file '/opt/homebrew/opt/openresty/lualib/resty/http.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/http.ljbc' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/http/init.ljbc' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/lualib/resty/http.ljbc' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/lualib/resty/http/init.ljbc' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/http.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/http/init.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/lualib/resty/http.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/lualib/resty/http/init.lua' no file './resty/http.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/luajit/share/luajit-2.1/resty/http.lua' no file '/usr/local/share/lua/5.1/resty/http.lua' no file '/usr/local/share/lua/5.1/resty/http/init.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/luajit/share/lua/5.1/resty/http.lua' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/luajit/share/lua/5.1/resty/http/init.lua' no file '/opt/homebrew/opt/openresty/lualib/resty/http.so' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/http.so' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/lualib/resty/http.so' no file './resty/http.so' no file '/usr/local/lib/lua/5.1/resty/http.so' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/luajit/lib/lua/5.1/resty/http.so' no file '/usr/local/lib/lua/5.1/loadall.so' no file '/opt/homebrew/opt/openresty/lualib/resty.so' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty.so' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/lualib/resty.so' no file './resty.so' no file '/usr/local/lib/lua/5.1/resty.so' no file '/opt/homebrew/Cellar/openresty/1.27.1.2_1/luajit/lib/lua/5.1/resty.so' no file '/usr/local/lib/lua/5.1/loadall.so' stack traceback: coroutine 0:
最新发布
09-15
<think> 我们已经在OpenResty环境中使用opm安装了ledgetech/lua-resty-http,但运行时仍出现"module 'resty.http' not found"错误。这个问题通常是由于OpenResty的包路径配置不正确导致的。以下是完整的解决方案: ### 一、问题原因分析 1. **路径不匹配**:opm默认安装路径为`/usr/local/openresty/site/lualib`,但OpenResty默认搜索路径可能未包含该目录 2. **环境变量缺失**:未正确设置`lua_package_path`变量 3. **权限问题**:OpenResty进程用户无权限访问模块文件 ### 二、解决方案步骤 #### 步骤1:验证实际安装路径 执行以下命令确认模块位置(注意根据你的OpenResty安装路径调整): ```bash # Homebrew安装路径(macOS) ls /opt/homebrew/opt/openresty/site/lualib/resty/http* # 标准安装路径(Linux) ls /usr/local/openresty/site/lualib/resty/http* ``` ✅ 正确输出应包含: ``` http.lua http_connect.lua http_headers.lua ``` #### 步骤2:配置OpenResty加载路径 在nginx配置的http块中添加路径声明(路径根据实际安装位置调整): ```nginx http { # 添加以下配置(Homebrew安装示例) lua_package_path "/opt/homebrew/opt/openresty/site/lualib/?.lua;;"; # 标准Linux安装使用 # lua_package_path "/usr/local/openresty/site/lualib/?.lua;;"; server { location /test { content_by_lua_block { local http = require "resty.http" -- 现在应能正确加载 -- 测试代码... } } } } ``` #### 步骤3:检查文件权限 确保OpenResty进程用户(通常是nginx用户)有读取权限: ```bash sudo chmod -R o+r /opt/homebrew/opt/openresty/site/lualib/resty ``` #### 步骤4:配置生效验证 1. 测试nginx配置: ```bash sudo openresty -t ``` 2. 重载配置: ```bash sudo openresty -s reload ``` ### 三、快速测试脚本 创建测试接口验证功能: ```nginx location /http-test { content_by_lua_block { local http = require "resty.http" local httpc = http.new() local ok, err = httpc:connect("example.com", 80) if not ok then ngx.say("Connection failed: ", err) return end ngx.say("Successfully loaded lua-resty-http!") httpc:close() } } ``` 访问`/http-test`应输出:`Successfully loaded lua-resty-http!` ### 四、高级配置技巧 1. **多路径配置**(推荐): ```nginx lua_package_path "/usr/local/openresty/lualib/?.lua;/opt/openresty/site/lualib/?.lua;;"; ``` 2. **开发环境调试**: 在nginx启动前设置环境变量: ```bash export LUA_PATH='/opt/homebrew/opt/openresty/site/lualib/?.lua;;' openresty ``` > 注:OpenResty的包加载机制遵循Lua标准,路径配置错误是此问题的最常见原因[^1][^2] --- ### 相关问题 1. 如何为不同server块设置独立的lua_package_path? 2. 使用opm安装的模块在Kubernetes环境中如何持久化? 3. lua-resty-http与OpenResty自带的ngx.location.capture有何区别? 4. 如何验证lua-resty-http的SSL/TLS证书链完整性? [^1]: 路径配置必须包含最后的`;;`,表示保留默认搜索路径 [^2]: macOS系统使用Homebrew安装时,路径通常为`/opt/homebrew/opt/openresty/...` </think> 以下针对 "module 'resty.http' not found" 错误的完整解决方案,结合您已安装 `ledgetech/lua-resty-http` 的情况: ### 一、核心解决方案 **问题根源**:OpenResty 未正确加载模块路径 **解决步骤**: 1. **确认实际安装路径**(替换 `/opt/homebrew/...` 为您的路径): ```bash # 查看安装文件 ls /opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/http* ``` ✅ 应输出三个文件: `http.lua` `http_connect.lua` `http_headers.lua` 2. **修改 Nginx 配置**: 在 `nginx.conf` 的 `http` 块中添加路径声明: ```nginx http { # 添加此行(路径根据实际安装位置调整) lua_package_path "/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/?.lua;;"; server { location / { content_by_lua_block { local http = require "resty.http" -- 现在应正常加载 -- 您的代码... } } } } ``` 3. **验证配置并重启**: ```bash sudo openresty -t # 测试配置 sudo openresty -s reload # 热重载 ``` ### 二、备选方案(若仍失败) #### 方案1:环境变量配置 ```bash # 临时生效(启动前设置) export LUA_PATH="/opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/?.lua;;" sudo openresty ``` #### 方案2:符号链接到默认路径 ```bash sudo ln -s /opt/homebrew/Cellar/openresty/1.27.1.2_1/site/lualib/resty/* /usr/local/openresty/lualib/resty/ ``` ### 三、快速测试脚本 创建测试文件 `test_http.lua`: ```lua local http = require "resty.http" local httpc = http.new() -- 测试连接 local ok, err = httpc:connect("example.com", 80) if not ok then print("ERROR: ", err) return end print("SUCCESS: resty.http loaded!") httpc:close() ``` 运行验证: ```bash resty test_http.lua ``` ✅ 成功输出:`SUCCESS: resty.http loaded!` ### 四、根本原因分析 | 原因 | 发生概率 | 典型场景 | |------|----------|----------| | 路径未配置 | 85% | Homebrew 安装的 OpenResty | | 权限问题 | 10% | 使用 `sudo` 安装但普通用户运行 | | 版本冲突 | 5% | 多版本 OpenResty共存 | > 注:Homebrew 安装的 OpenResty 默认路径与标准路径不同,必须显式配置 `lua_package_path`[^1][^2] --- ### 相关问题 1. 如何为不同项目配置独立的 OpenResty 模块路径? 2. 使用 Docker 部署时如何持久化 lua-resty-http 配置? 3. 如何验证 lua-resty-http 与当前 OpenResty 版本的兼容性? 4. 多版本 Lua 模块共存时如何避免冲突? [^1]: Homebrew 安装路径通常为 `/opt/homebrew/opt/openresty`(Apple Silicon)或 `/usr/local/opt/openresty`(Intel Mac) [^2]: 配置中的双分号 `;;` 表示保留默认搜索路径
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值