import os
import sys
import hashlib
import hmac
import base64
import urllib
import time
import uuid
import requests
import json

def get_iso8601_time():
    '''返回iso8601格式的时间'''
    TIME_ZONE = "GMT"
    FORMAT_ISO8601 = "%Y-%m-%dT%H:%M:%SZ"
    return time.strftime(FORMAT_ISO8601, time.gmtime())

def get_uuid():
    '''返回uuid'''
    return str(uuid.uuid4())

def get_parameters(user_param, Action, AccessKeyId, Version):
    '''
    拼接参数字典
    user_param: {"RegionId":"cn-beijing", "LoadBalancerName":"test-xxxx", "AddressType":"intranet", "VSwitchId":"vsw-xxxxxxxx"}
    Action操作例如:CreateLoadBalancer
    AccessKeyId:access key ID
    Version: 接口的版本
    '''
    parameters = {}
    parameters['HTTPMethod'] = 'POST'
    parameters['AccessKeyId'] = AccessKeyId
    parameters['Format'] = 'json'
    parameters['Version'] = Version
    parameters['SignatureMethod'] = 'HMAC-SHA1'
    parameters['Timestamp'] = get_iso8601_time()
    parameters['SignatureVersion'] = '1.0'
    parameters['SignatureNonce'] = get_uuid()
    parameters['Action'] = Action
    for (k, v) in sorted(user_param.items()):
        parameters[k] = v
    return parameters

def get_param(parameters):
    '''把公共参数拼接成字符串'''
    param_str = ''
    for (k, v) in sorted(parameters.items()):
        param_str += "&" + urllib.parse.quote(k, safe='') + "=" + urllib.parse.quote(v, safe='')
    param_str = param_str[1:]
    return param_str

def get_StringToSign(parameters, param_str):
    '''拼接生成签名的字符串'''
    StringToSign = parameters['HTTPMethod'] + "&%2F&" + urllib.parse.quote(param_str, safe='')
    return StringToSign

def get_signature(StringToSign, AccessKeySecret):
    '''构建签名'''
    h = hmac.new(bytes(AccessKeySecret,'utf-8'), bytes(StringToSign,'utf-8'), hashlib.sha1)
    signature = base64.encodebytes(h.digest()).strip()
    return str(signature,'utf-8') 

def build_request(server_url, param_str, signature, AccessKeySecret):
    '''拼接url并进行请求'''
    Signature = "Signature=" + urllib.parse.quote(signature)
    param = param_str + "&" + Signature
    request_url = server_url + param
    print(request_url)
    s = requests.post(request_url)
    print(s.content)
    print(s)
    return(s)

def get_regions(server_url, Action, user_param, AccessKeySecret, AccessKeyId, Version):
    '''对请求进行模块
    server_url: vpc.aliyun.com
    Action = 'AssociateEipAddress'
    AccessKeySecret, AccessKeyId:也就是ak
    user_param = {'RegionId': 'cn-xxxxxx','InstanceId':'eip-wzxxxxxgxxxxhyn','Mode':'BINDED'}
    Version:API版本号,使用YYYY-MM-DD日期格式。取值:
    2016-04-28
    '''
    server_url = 'https://' + server_url + '/?'
    AccessKeySecret = AccessKeySecret
    AccessKeyId = AccessKeyId
    parameters = get_parameters(user_param, Action, AccessKeyId, Version)
    param_str = get_param(parameters)
    StringToSign = get_StringToSign(parameters, param_str)
    signature = get_signature(StringToSign, AccessKeySecret + '&')
    Message = build_request(server_url, param_str, signature, AccessKeySecret)
    return Message

#阿里云AK密钥
AccessKeyId='xxxxxxx'
AccessKeySecret='xxxxxx'

    #调用的接口
Action = 'SendSms'
    #需要提交的请求参数
user_param = {'PhoneNumbers': '+861x77705939x','SignName':'XXX','TemplateCode':'SMS_124594021','TemplateParam':'{\"content\":\"2亲爱的xx粉,您在xxxx官网订购的xxxx未完成支付,今日购享0首付花呗分期,更有限时购机好礼,立刻支付锁定购机礼赠,点击支付:http://t.xxxx 退订回T\"}'}

    #接口URL
server_url = 'dysmsapi.aliyuncs.com'

    #接口版本,官方文档中查看
Version = '2017-05-25'

message = get_regions(server_url, Action, user_param, AccessKeySecret, AccessKeyId, Version)

#print ("============================================{}" .format(message.text))
#print ("********************************************{}\n\n\n\n" .format(message.content))