1
|
|
|
# -*- coding: utf-8 -*- |
2
|
10 |
|
from __future__ import absolute_import, unicode_literals |
3
|
10 |
|
import copy |
4
|
10 |
|
import hashlib |
5
|
10 |
|
import socket |
6
|
|
|
|
7
|
10 |
|
import six |
8
|
|
|
|
9
|
10 |
|
from wechatpy.utils import to_binary, to_text |
10
|
|
|
|
11
|
|
|
|
12
|
10 |
|
def format_url(params, api_key=None): |
13
|
10 |
|
data = [to_binary('{0}={1}'.format(k, params[k])) for k in sorted(params) if params[k]] |
14
|
10 |
|
if api_key: |
15
|
10 |
|
data.append(to_binary('key={0}'.format(api_key))) |
16
|
10 |
|
return b"&".join(data) |
17
|
|
|
|
18
|
|
|
|
19
|
10 |
|
def calculate_signature(params, api_key): |
20
|
10 |
|
url = format_url(params, api_key) |
21
|
10 |
|
return to_text(hashlib.md5(url).hexdigest().upper()) |
22
|
|
|
|
23
|
|
|
|
24
|
10 |
|
def _check_signature(params, api_key): |
25
|
|
|
_params = copy.deepcopy(params) |
26
|
|
|
sign = _params.pop('sign', '') |
27
|
|
|
return sign == calculate_signature(_params, api_key) |
28
|
|
|
|
29
|
|
|
|
30
|
10 |
|
def dict_to_xml(d, sign): |
31
|
10 |
|
xml = ['<xml>\n'] |
32
|
10 |
|
for k in sorted(d): |
33
|
|
|
# use sorted to avoid test error on Py3k |
34
|
10 |
|
v = d[k] |
35
|
10 |
|
if isinstance(v, six.integer_types) or (isinstance(v, six.string_types) and v.isdigit()): |
36
|
10 |
|
xml.append('<{0}>{1}</{0}>\n'.format(to_text(k), to_text(v))) |
37
|
|
|
else: |
38
|
10 |
|
xml.append( |
39
|
|
|
'<{0}><![CDATA[{1}]]></{0}>\n'.format(to_text(k), to_text(v)) |
40
|
|
|
) |
41
|
10 |
|
xml.append('<sign><![CDATA[{0}]]></sign>\n</xml>'.format(to_text(sign))) |
42
|
10 |
|
return ''.join(xml) |
43
|
|
|
|
44
|
|
|
|
45
|
10 |
|
def get_external_ip(): |
46
|
10 |
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
47
|
10 |
|
try: |
48
|
10 |
|
wechat_ip = socket.gethostbyname('api.mch.weixin.qq.com') |
49
|
10 |
|
sock.connect((wechat_ip, 80)) |
50
|
10 |
|
addr, port = sock.getsockname() |
51
|
10 |
|
sock.close() |
52
|
10 |
|
return addr |
53
|
|
|
except socket.error: |
54
|
|
|
return '127.0.0.1' |
55
|
|
|
|