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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值