当前位置:   article > 正文

【微信小程序H5】linux多服务器部署 一套测试服务 如何兼容小程序和H5正常登录 微信小程序和H5通过code换取accessToken

【微信小程序H5】linux多服务器部署 一套测试服务 如何兼容小程序和H5正常登录 微信小程序和H5通过code换取accessToken

背景介绍

1、我们只有一个备案的域名+服务器,如何在多个未备案的服务器进行测试环境,调试?
2、通过一套服务,如何调试小程序 和 微信web ?

一、配置

1、公众号配置

1.1、IP白名单配置

这里会给一个 .txt 文件配置到服务器(Nginx)内
如:MP_verify_vNlvxxxxxx54E.txt

在这里插入图片描述

1.2、域名配置

这个域名必须是备案的

在这里插入图片描述

1.3、人员设置

调试开发的人员就需要在这里添加

在这里插入图片描述

1.4、web开发者工具

在web开发工具允许使用的用户

在这里插入图片描述
在这里插入图片描述

二、通过 Nginx 转发

1、服务器+域名配置

服务器A:192.168.0.1 (prod)
服务器B:192.168.0.2 (小程序、H5测试)
域名:www.xxx.xxx
DNS:www.xxx.xxx -> 192.168.0.1
Nginx:安装在 192.168.0.1

2、Nginx配置

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    client_max_body_size 10M; # 设置请求体最大大小为20兆
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';

    include /etc/nginx/conf.d/*.conf;

    server {
        listen 80;
        # 一、这里填写你的实际域名
        server_name www.xxx.xxx;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        # 二、这里填写你的实际域名(同一)
        server_name www.xxx.xxx;

		# 三、配置你的SSL证书
        ssl_certificate /home/ctra/www.xxx/www.xxx.xxx_bundle.crt;
        ssl_certificate_key /home/ctra/www.xxx/www.xxx.xxx.key;

		# 四、当前服务转发配置(如果需要)
        location /ctra-weixin {
            proxy_pass http://127.0.0.1:8002;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
        
        # 五、配置微信web秘钥
        location = /MP_verify_vNlxxxx4E.txt {
        	   add_header  Content-Type  "text/plain";
        	   root /etc/nginx;
	    }

        # 六、微信web的调试路径和主页面
	    root /home/ctra;
	    index index.html;
	
	    # 七、使用 history方式路由(如果需要)
	    location / {
	        try_files $uri $uri/ /index.html;
	    }

		# 八、转发到 服务器B:192.168.0.2 ,且重写路由
	    location /api {
	    	rewrite ^/api(.*)$ $1 break;
            proxy_pass http://192.168.0.2:8082;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
	
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

总结:
上面从 一~八 一共8处设置的位置
尤其是第8点,我们可以通过当前的nginx转发到服务器B
实现了即有ssl又可以不破坏prod服务,使用我们测试的服务

上面代码中的 index.html 代码如下:

<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="/assets/uni.2bfcb74d.css">

    <meta charset="UTF-8" />
    <script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.9.0/vconsole.min.js"></script>
    <script>
      new VConsole();
    </script>
    <script>
      var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'));
      document.write(
        '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
          (coverSupport ? ', viewport-fit=cover' : '') +
          '" />',
      );
    </script>
    <title></title>
    <!--preload-links-->
    <!--app-context-->
    <script type="module" crossorigin src="/assets/index-4c468109.js"></script>
    <link rel="stylesheet" href="/assets/index-15922558.css">
  </head>
  <body>
    <div id="app"><!--app-html--></div>
    
  </body>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

3、获得 Code

3.1、小程序

需要前端同事打包成dist 然后让小程序加载获取

在这里插入图片描述

3.2、微信web H5

1)换取code

我们可以得到一个链接
https://open.weixin.qq.com/connect/oauth2/authorize?
拼接

  • appid
  • redirect_uri
  • response_type
  • scope=snsapi_user
  • state=STATE
  • connect_redirect
  • uin
  • key
  • pass_ticket
https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的APP_ID&redirect_uri=https://xxx.xxx/&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1&uin=微信accessToken秘钥%3D%3D&key=查询文档获取&pass_ticket=查询文档获取
  • 1

通过链接我们可以换取code

2)换取accesstoken

https://api.weixin.qq.com/sns/oauth2/access_token

以下为go代码示例:

func (l *AuthorizetionGzhLogic) AuthorizetionGzh(req *types.AuthorizetionReq) (resp *types.CommonDetailResp, err error) {
	// 公众号请求配置
	gzh := gochat.NewOffia(constant.WEIXIN_APP_ID, constant.WEIXIN_APP_SECRET)

	//通过code 换取 openid
	mini, err := gzh.Code2OAuthToken(l.ctx, req.Code)
	if err != nil {
		logx.WithContext(l.ctx).Errorf(err.Error())
		return nil, errorx.NewCodeAbortedError("该code已经失效或错误!")
	}

	//fmt.Println("--------------------marshal:", string(marshal))
	l.Logger.Infof("OpenID:%s,AccessToken:%s", mini.OpenID, mini.AccessToken)
	data := make(map[string]interface{})
	//var data map[string]interface{}
	data["access_token"] = mini.AccessToken
	data["refresh_token"] = mini.RefreshToken
	data["expires_in"] = mini.ExpiresIn
	data["openid"] = mini.OpenID
	data["scope"] = mini.Scope
	return &types.CommonDetailResp{Code: xerr.OK, Msg: xerr.MapErrMsg(xerr.OK), Data: data}, nil

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
3)换取 服务登录 token

https://api.weixin.qq.com/sns/userinfo?access_token

参数如下:(openid、accessToken为上一步获取)

{
    "accessToken": "Excepteur laboris",
    "lang": "ut ipsum exercitation",
    "openid": "7"
}
  • 1
  • 2
  • 3
  • 4
  • 5

以下为go代码片段:

可见返回的key如下

httpClient := &http.Client{} // You can customize the HTTP client if needed
	userInfo, err := oauth2.GetUserInfo(req.AccessToken, req.Openid, req.Lang, httpClient)
	if err != nil {
		return nil, err
	}

	res := map[string]interface{}{}
	res["province"] = userInfo.Province
	res["nickname"] = userInfo.Nickname
	res["city"] = userInfo.City
	res["country"] = userInfo.Country
	res["sex"] = userInfo.Sex
	res["headImageURL"] = userInfo.HeadImageURL
	res["openId"] = userInfo.OpenId
	res["unionId"] = userInfo.UnionId
	res["privilege"] = userInfo.Privilege
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/175548
推荐阅读
相关标签
  

闽ICP备14008679号