小程序根據referer跳轉不一樣的後臺環境

1、問題:

開發小程序的時候有4個版本(開發、體驗、審覈、正式)。因此不一樣的環境要請求不一樣的後臺。特別是審覈版本,由於還要微信審覈,若是請求錯誤,會被審覈失敗。由於生產環境是對應舊的後臺版本,因此審覈版本既不能調到後臺生產環境,也不能跳到開發環境。
咱們爲了方便生產審覈2個版本小程序都去請求/prod。這裏就要區別真實的請求究竟是從生產審覈哪裏來的。html

2、解決思路。

微信給咱們服務器發送請求wx.request的會帶上一個referer的header參數。格式以下:nginx

https://servicewechat.com/<appId>/<version>/page-frame.html

其中<appId>是發送請求的小程序appId,<version>是小程序的版本。小程序

  • 開發體驗審覈 版本中version值是0,開發工具中version值是devtools
  • 正式版的version值是大於0的正整數,表示這個小程序發佈到正式版多少次。 例子以下:
開發版:
https://servicewechat.com/小程序appId/0/page-frame.html
體驗版:
https://servicewechat.com/小程序appId/0/page-frame.html
devtools:
https://servicewechat.com/小程序appId/devtools/page-frame.html
正式版:
https://servicewechat.com/小程序appId/6/page-frame.html

3、解決方式。經過nginx作服務器選擇。

一、定義一個變量 foo, 配置一個map,把http_referer映射到foo

map $http_referer $foo {
	default   "prod";
	~^https://servicewechat.com/[^/]+/0/(.*)$ "dev";
	~^https://servicewechat.com/[^/]+/devtools/(.*)$ "dev";
}

二、配置服務器。

upstream dev {
     server localhost:7777;
}
upstream prod {
    server localhost:9999;
}

三、location 中使用 foo變量, 導航到正確的地址。

這裏我用add_headerfoo變量輸出一下,做爲測試。api

location / {
            #set $foo "$http_referer";
            add_header wkfoo 'foo: $foo "$http_referer"';
            proxy_pass   http://$foo;
        }

四、測試一下。

curl -H 'Cache-Control: no-cache' -I "https://xxx.xxx.com/prod/xxx?參數1=xxx&參數2=xxx" --referer "https://servicewechat.com/xxx/devtools/page-frame.html"
curl -H 'Cache-Control: no-cache' -I "https://xxx.xxx.com/prod/xxx?參數1=xxx&參數2=xxx" --referer "https://servicewechat.com/xxx/0/page-frame.html"

其餘。

實際上這裏小程序請求後臺的時候,應該加上一個api的版本號。服務器

參考文章:
https://developers.weixin.qq.com/community/develop/article/doc/0004e2dffb0f98852cf7183285b013微信

相關文章
相關標籤/搜索