python develop micro-channel public number [1] backend server is configured with a number of public development configuration

Updated: March 7 2020

Hardware Prerequisite public microcells number developed: (1) a public application No. (2) a public network server ip (preferably Ali cloud, cloud server Tencent cloud like) (3) resolved to (2) the server a domain name address (Ali cloud, cloud Tencent can buy).

1. No application for micro-channel public

Individuals can apply for subscription number, application tutorial reference: https://jingyan.baidu.com/article/020278113d07531bcc9ce5a5.html

2. The back-end server configuration

Micro-channel public number is only the equivalent traffic forwarding, to achieve specific functions required to achieve up specific back-end server. The public began to support micro-channel number only domain names (ip does not support direct access, this is the reason why the domain name), only support port 80 (http) or port 443 (https)

2.1 nginx installation and configuration

Software provides the back-end server requires a web server function, we use nginx, more convenient.
Installation process:
(1) installing gcc (gcc -v can use to see if gcc installed):

yum -y install gcc

(2) Installation depends:

yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel

(3) Download nginx

wget http://nginx.org/download/nginx-1.9.9.tar.gz  

(4) extracting installation

tar -zxvf  nginx-1.9.9.tar.gz

After the extraction is complete access to the folder

cd nginx-1.9.9

Install, run under the administrator account:

./configure
 
make
 
make install

Enter the domain name in the browser: After www.xxxxx.cn:
Here Insert Picture Description
(5) nginx configuration
because the public micro-channel number can only use port 80 or port 433, so we can use nginx do port forwarding, so that the server be fully utilized.
In nginx.conf file ( vim /usr/local/nginx/conf/nginx.conf) were added in the following code:

		# hsb_signal_tower
        location /data/hsb_signal_tower {
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Scheme $scheme;
            proxy_pass http://127.0.0.1:8000;
        }

Such access www.xxxx.cn/data/hsb_signal_tower will be forwarded to port 8000, port 8000 after his subordinates development services.

2.2 python installation

yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel  libffi-devel 
# 下载文件后执行下面的操作
   #释放文件:
   tar -xvzf Python-3.5.1.tgz
   #进入目录:
   cd Python-3.5.1/
   # 添加配置:
   ./configure --prefix=/usr/local/python3
   # 这里配置自己的安装目录,接下来编译源码:
   make
   # 执行安装:
   make install

   # 重新建立连接
   mv /usr/bin/python /usr/bin/python.bak
   ln -s /usr/local/python3/bin/python3 /usr/bin/python

   #配置yum,因为yum是基于python2的
   vim /usr/bin/yum
   把#! /usr/bin/python修改为#! /usr/bin/python2

   vim /usr/libexec/urlgrabber-ext-down
   把#! /usr/bin/python 修改为#! /usr/bin/python2

   # 添加环境量
   vim .bashrc
   export PATH=/usr/local/python3/bin:$PATH

   # pip3 软连接到pip
   ln -s /usr/local/python3/bin/pip3 /usr/bin/pip

Public No. 3 Configuration

This two parts together, the micro-channel corresponds to the communication public verification number to the backend server. No end micro letter public a unique token, this token validation on the server side to complete the entire communication verification. token is unique, so must be kept confidential.

No. 3.1 micro-channel public side configuration

(1) into the public pulled the bottom number, enter the basic configuration.
Here Insert Picture Description(2) fill in the information
Here Insert Picture Description(a) url fill in the domain name must be consistent with the nginx configuration
(b) token in to fill out, which is a unique identifier number of public development, keep in mind.
(C) third point randomly generated.
Do not submit After filling, the next to build an authentication service on the server side.

3.2 server-side validation service building

This example uses flask build web applications
python code below, file name:. Wechat.py is used to modify their own token. :

# coding:utf-8
from flask import Flask, request, abort, render_template
import hashlib
import xmltodict
import time
# 用它可以访问http请求地址
import urllib.request as urllib2
import urllib
import json

# 微信的token令牌
WECHAT_TOKEN = 'your token'
app = Flask(__name__)

@app.route("/data/hsb_signal_tower", methods=["GET", "POST"])
def wechat():
    """验证服务器地址的有效性"""
    # 开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带四个参数:
    # signature:微信加密, signature结合了开发者填写的token参数和请求中的timestamp参数 nonce参数
    # timestamp:时间戳(chuo这是拼音)
    # nonce: 随机数
    # echostr: 随机字符串
    # 接收微信服务器发送参数
    signature = request.args.get("signature")
    timestamp = request.args.get("timestamp")
    nonce = request.args.get("nonce")

    # 校验参数
    # 校验流程:
    # 将token、timestamp、nonce三个参数进行字典序排序
    # 将三个参数字符串拼接成一个字符串进行sha1加密
    # 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
    if not all([signature, timestamp, nonce]):
        # 抛出400错误
        abort(400)

    # 按照微信的流程计算签名
    li = [WECHAT_TOKEN, timestamp, nonce]
    # 排序
    li.sort()
    # 拼接字符串
    tmp_str = "".join(li)
    tmp_str = tmp_str.encode('utf-8')

    # 进行sha1加密, 得到正确的签名值
    sign = hashlib.sha1(tmp_str).hexdigest()

    # 将自己计算的签名值, 与请求的签名参数进行对比, 如果相同, 则证明请求来自微信
    if signature != sign:
        # 代表请求不是来自微信
        # 弹出报错信息, 身份有问题
        abort(403)
    else:
        # 表示是微信发送的请求
        if request.method == "GET":
            # 表示第一次接入微信服务器的验证
            echostr = request.args.get("echostr")
            # 校验echostr
            if not echostr:
                abort(400)
            return echostr

        elif request.method == "POST":
            # 表示微信服务器转发消息过来
            # 拿去xml的请求数据
            xml_str = request.data

            # 当xml_str为空时
            if not xml_str:
                abort(400)

            # 对xml字符串进行解析成字典
            xml_dict = xmltodict.parse(xml_str)

            xml_dict = xml_dict.get("xml")

            # MsgType是消息类型 这里是提取消息类型
            msg_type = xml_dict.get("MsgType")

            if msg_type == "text":
                # 表示发送文本消息
                # 够造返回值, 经由微信服务器回复给用户的消息内容
                # 回复消息
                # ToUsername: (必须传) 接收方账号(收到的OpenID)
                # FromUserName: (必须传) 开发者微信号
                # CreateTime: (必须传) 消息创建时间(整形)
                # MsgType: (必须传) 消息类型
                # Content: (必须传) 回复消息的内容(换行:在Content中能够换行, 微信客户端就支持换行显示)

                resp_dict = {
                    "xml":{
                        "ToUserName":xml_dict.get("FromUserName"),
                        "FromUserName":xml_dict.get("ToUserName"),
                        "CreateTime":int(time.time()),
                        "MsgType":"text",
                        "Content":xml_dict.get("Content")
                    }
                }
            else:
                resp_dict = {
                    "xml": {
                        "ToUserName": xml_dict.get("FromUserName"),
                        "FromUserName": xml_dict.get("ToUserName"),
                        "CreateTime": int(time.time()),
                        "MsgType": "text",
                        "Content": "对不起,不能识别您发的内容!"
                    }
                }
            # 将字典转换为xml字符串
            resp_xml_str = xmltodict.unparse(resp_dict)
            # 返回消息数据给微信服务器
            return resp_xml_str
if __name__ == '__main__':
    app.run(port=8000, debug=True)

The code above with reference to the god of the blog, the original blog use python2, the above code applies python3. Then use the command: python wechat.pyno error and the following message indicates that there is no problem:
Here Insert Picture Description
after a configuration page (1) Click the submit button, you will be prompted if the validation fails validation token fails, then there will be a corresponding server-side error. If the validation is successful, the user can send messages in a public number, the number will return to the public to send information.
I hope you patiently debugging.

Published 111 original articles · won praise 185 · Views 3.12 million +

Guess you like

Origin blog.csdn.net/jinxiaonian11/article/details/104708996