Completed
Pull Request — master (#138)
by
unknown
20:13
created

wechatpy.pay.dict_to_xml()   A

Complexity

Conditions 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

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