企业微信小程序应用对接

2020-07-24  本文已影响0人  霡霂976447044

使用https://github.com/neo20/BizWxCryptor/blob/master/BizWxUtil.py实现, Flask.

提供的接口回调请求的数据也是乱七八糟的,又有xml又有json,xml解析也是,文档说的也是含糊

校验服务器数据回调URL

 if request.method == 'GET':
        print(request.json)
        print(request.args)

        msg_signature = request.args.get('msg_signature')
        timestamp = request.args.get('timestamp')
        nonce = request.args.get('nonce')
        echostr = request.args.get('echostr')
        aa = WXBizMsgCrypt('关联小程序配置页面TOKEN', '关联小程序配置页面EncodingAESKey', 'CorpID 在服务商信息->基本信息找')
        ret, msg = aa.VerifyURL(msg_signature, timestamp, nonce, echostr)
        print('cccccccccccc', ret, msg)
        return msg

获取第三方应用凭证(suite_access_token)

文档1

文档2

截图_2020-07-24_17-11-14ssss.png

微信会定时上传suite_ticket到你的服务器回调接口,也可以手动刷新手动触发回调,微信会xml格式的消息上传,
同样这个消息需要解密,解密之后xml数据里面会有SuiteTicket数据,这个数据保存到服务器本地,例如redis

然后就是请求得到suite_access_token, 此处返回json格式

http https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token suite_id=xxx suite_secret=xxx suite_ticket=o
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 171
Content-Type: application/json; charset=UTF-8
Date: Fri, 24 Jul 2020 05:52:56 GMT
Error-Code: 0
Error-Msg: ok
Server: nginx

{
    "expires_in": 7200,
    "suite_access_token": "xxxxxxxxxxxx"
}

同样的,suite_access_token 也自己需要保存,两小时失效

指令回调URL

以企业绑定你的小程序为例,会回调指令回调URL 并且是POST请求

通用步骤基本上是解密xml消息格式,然后根据消息类型,做具体的业务判断,

        encrypted_xml = request.get_data().decode('utf-8')  # 加密过的xml消息体 里面有关键数据
        sVerifyMsgSig = request.args.get('msg_signature')
        sVerifyNonce = request.args.get('nonce')
        sVerifyTimeStamp = request.args.get('timestamp')

        print('body', encrypted_xml)

        wxcpt = WXBizMsgCrypt('Token', 'EncodingAESKey', 'SuiteID')  # 注意第三个参数SuiteID
        ret, xml_content = wxcpt.DecryptMsg(encrypted_xml, sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce)
        if ret != 0:
            print("ERR: VerifyURL ret: " + str(ret))
            return "ERR: VerifyURL ret: " + str(ret)
        xml_tree = ET.fromstring(xml_content)
        print("xml_content: ", xml_content)
        # return xml_content
        type_name = xml_tree.find("InfoType").text

        print('typename', type_name)  # 如果是绑定的信息 打印是create_auth

        # 
        SUITE_ACCESS_TOKEN = 'xxxxx'
        url = f'https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token={SUITE_ACCESS_TOKEN}'
        auth_code = xml_tree.find("AuthCode").text  # 得到解密过的xml数据中AuthCode,来获取企业数据
        print('auth_code', auth_code)
        resp = requests.post(url, json={
            "auth_code": auth_code
        }).json()
        print('resp', resp)
  

        return "success"  # 一定要返回success!!!!
上一篇下一篇

猜你喜欢

热点阅读