forked from yuzeming/CEACStatTracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwechat.py
68 lines (58 loc) · 2.43 KB
/
wechat.py
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
from datetime import datetime, timedelta
import requests
from xml.etree import ElementTree
import os
import yaml
from hashlib import sha1
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yaml")
if os.path.exists(config_path):
config = yaml.safe_load(open(config_path))
def check_wx_signature(signature, timestamp, nonce, token):
if not signature or not timestamp or not nonce or not token:
return False
if datetime.timestamp(datetime.now()) - float(timestamp) > 30:
return False
args = [token, timestamp, nonce]
args.sort()
m = sha1(("".join(args)).encode()).hexdigest()
if m != signature:
return False
return True
def xmltodict(xml_string):
root = ElementTree.fromstring(xml_string)
ret = [(child.tag, child.text) for child in root]
return dict(ret)
def get_access_token():
if config.get("accessToken","") and config["tokenExpires"] > datetime.now():
return config["accessToken"]
url = "https://api.weixin.qq.com/cgi-bin/token"
ret = requests.get(url, {"grant_type": "client_credential", "appid": config["appID"], "secret": config["appSecret"]}).json()
if "errcode" in ret:
raise Exception(ret["errmsg"])
config["accessToken"] = ret["access_token"]
config["tokenExpires"] = timedelta(seconds=ret["expires_in"] - 300) + datetime.now()
yaml.dump(config, open("config.yaml","w"))
return config["accessToken"]
'''
ArFK9lrJ57rW4t4QQ6bqtdt8IFsLFZkLlPfrHI5hlCo
{{first.DATA}}
订单编号:{{keyword1.DATA}}
订单状态:{{keyword2.DATA}}
{{remark.DATA}}
'''
def wechat_msg_push(touser, tempID=config["tempID"], msg_url="", **kwargs):
url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={ACCESS_TOKEN}".format(
ACCESS_TOKEN=get_access_token())
data = {}
for k,v in kwargs.items():
data[k] = {"value": v}
post_json = {"touser": touser, "template_id": tempID, "data": data, "url": msg_url}
requests.post(url=url, json=post_json)
def get_qr_code_url(scene_str):
url = " https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={ACCESS_TOKEN}".format(
ACCESS_TOKEN=get_access_token())
post_json = {"expire_seconds": 2592000, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": scene_str}} }
ret = requests.post(url=url, json=post_json).json()
if "errcode" in ret:
raise RuntimeError(ret["errmsg"])
return ret["url"]