小程序根据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微信

相关文章
相关标签/搜索