django中基於python3.6使用容聯發送短信

一. Django基於python3.6使用容聯發送短信流程

  容聯官方的python支持2.7版本,當咱們python解釋器採用3版本時,須要修改容聯接口中的一些參數及方法。python

  首先去容聯官網註冊帳號,申請測試帳號無需實名認證,並且開始帳號自帶8元錢,一條短信大概2分。web

1.1 調用接口前的準備

  首先註冊登陸以後再控制檯中添加測試號碼:
redis

  點擊導航欄的開發文檔:
數據庫

  選擇短信開發手冊:django

  以後點擊Demo示例:json

  下載基於python的Demo:api

  下載完成後解壓,將其中的兩個文件複製:服務器

  而後在python項目文件夾下新建文件夾,好比libs,裏面再新建一個文件夾,將這兩個文件黏貼在其中:
網絡

  而後在yuntongxun文件下新建sms.py文件,同時將接口調用示例中年的代碼複製黏貼至其中:app

  將sms.py中的報錯修改一下:

  以上幾個參數在控制檯中能夠看到:

  同時能夠修改一下sms.py文件中調用接口的函數,修改一下返回的信息,方便後續加入本身的邏輯,這裏我將其函數名也修改了:

def send_msg(to, datas, tempId):
    # 初始化REST SDK
    rest = REST(serverIP, serverPort, softVersion)
    rest.setAccount(accountSid, accountToken)
    rest.setAppId(appId)

    result = rest.sendTemplateSMS(to, datas, tempId)
    if result.get('statusCode') == '000000':
        print('發送成功')
        return True
    else:
        print('發送失敗')
        return False

  result中的信息能夠在開發文檔中查看:

1.2 使用容聯接口

  打開CCPRestSDK.py發現報錯:

  將其中的模塊修改以下,修改三個地方:

# 修改
from hashlib import md5
import base64
import datetime
# 修改
from urllib import request as urllib2
import json
# 修改
from .xmltojson import xmltojson
from xml.dom import minidom 

  而後裏面還有不少報錯以下:

  修改爲如下格式便可(將Exception後的逗號去掉改成as便可),將全部該報錯修改,共13個:

  而後將第定位至235行:

  首先修改生成sig中的內容:

#生成sig
signature = self.AccountSid + self.AccountToken + self.Batch;
md5_obj = md5()
md5_obj.md5.new(signature)
sig = md5_obj.hexdigest().upper()

   再修改生成auth中的內容:

# 僅僅修改其中的auth
auth = base64.encodebytes(src.encode()).decode().strip()

   再修改269行的代碼:

  修改以下:

req.data = body.encode()

   而後775行的代碼也須要加個類型轉換:

  使用Int將其轉爲整型:

if(int(self.ServerPort)<=0):
    print('172005');
    print('端口錯誤(小於等於0)');

  接着在yuntongxun文件夾下的__init__.py中加入如下語句:

from .sms import send_msg

   而後新建一個測試文件測試,須要搭建django測試環境,代碼以下:

import os

# 如下三行配置django測試環境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev')
import django
django.setup()

from luffyapi.libs.yuntongxun import send_msg

# send_msg('接收方手機號',(驗證碼,過時時間分鐘), 模塊編號)
# 模板編號測試環境中只能爲1,接收方手機號是咱們控制檯測試號碼中配置的
# 過時時間客戶端收到的是以分鐘爲單位的,咱們經過該值配置redis等非關係型數據庫中該驗證碼的過時時間
result = send_msg('15858291832', ('python', 5), 1)
print(result)
# -*- coding: UTF-8 -*-
#  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
#
#  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
#  that can be found in the LICENSE file in the root of the web site.
#
#   http://www.yuntongxun.com
#
#  An additional intellectual property rights grant can be found
#  in the file PATENTS.  All contributing project authors may
#  be found in the AUTHORS file in the root of the source tree.

from hashlib import md5
import base64
import datetime
from urllib import request as urllib2
import json
from .xmltojson import xmltojson


class REST:
    AccountSid = ''
    AccountToken = ''
    AppId = ''
    SubAccountSid = ''
    SubAccountToken = ''
    ServerIP = ''
    ServerPort = ''
    SoftVersion = ''
    Iflog = False  # 是否打印日誌
    Batch = ''  # 時間戳
    BodyType = 'xml'  # 包體格式,可填值:json 、xml

    # 初始化
    # @param serverIP       必選參數    服務器地址
    # @param serverPort     必選參數    服務器端口
    # @param softVersion    必選參數    REST版本號
    def __init__(self, ServerIP, ServerPort, SoftVersion):

        self.ServerIP = ServerIP
        self.ServerPort = ServerPort
        self.SoftVersion = SoftVersion

    # 設置主賬號
    # @param AccountSid  必選參數    主賬號
    # @param AccountToken  必選參數    主賬號Token

    def setAccount(self, AccountSid, AccountToken):
        self.AccountSid = AccountSid
        self.AccountToken = AccountToken

    # 設置子賬號
    #
    # @param SubAccountSid  必選參數    子賬號
    # @param SubAccountToken  必選參數    子賬號Token

    def setSubAccount(self, SubAccountSid, SubAccountToken):
        self.SubAccountSid = SubAccountSid
        self.SubAccountToken = SubAccountToken

    # 設置應用ID
    #
    # @param AppId  必選參數    應用ID

    def setAppId(self, AppId):
        self.AppId = AppId

    def log(self, url, body, data):
        print('這是請求的URL:')
        print(url)
        print('這是請求包體:')
        print(body)
        print('這是響應包體:')
        print(data)
        print('********************************')

    # 建立子帳號
    # @param friendlyName   必選參數      子賬號名稱
    def CreateSubAccount(self, friendlyName):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SubAccounts?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)
        # xml格式
        body = '''<?xml version="1.0" encoding="utf-8"?><SubAccount><appId>%s</appId>\
                <friendlyName>%s</friendlyName>\
                </SubAccount>\
                ''' % (self.AppId, friendlyName)

        if self.BodyType == 'json':
            # json格式
            body = '''{"friendlyName": "%s", "appId": "%s"}''' % (friendlyName, self.AppId)
        data = ''
        req.data = body.encode()
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    #  獲取子賬號
    # @param startNo  可選參數    開始的序號,默認從0開始
    # @param offset 可選參數     一次查詢的最大條數,最小是1條,最大是100條
    def getSubAccounts(self, startNo, offset):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/GetSubAccounts?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        # auth = base64.encodestring(src).strip()
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)
        # xml格式
        body = '''<?xml version="1.0" encoding="utf-8"?><SubAccount><appId>%s</appId>\
                <startNo>%s</startNo><offset>%s</offset>\
                </SubAccount>\
                ''' % (self.AppId, startNo, offset)

        if self.BodyType == 'json':
            # json格式
            body = '''{"appId": "%s", "startNo": "%s", "offset": "%s"}''' % (self.AppId, startNo, offset)
        data = ''
        req.data = body.encode()
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 子賬號信息查詢
    # @param friendlyName 必選參數   子賬號名稱

    def querySubAccount(self, friendlyName):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/QuerySubAccountByName?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        # auth = base64.encodestring(src).strip()
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)

        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?><SubAccount><appId>%s</appId>\
                <friendlyName>%s</friendlyName>\
                </SubAccount>\
                ''' % (self.AppId, friendlyName)
        if self.BodyType == 'json':
            body = '''{"friendlyName": "%s", "appId": "%s"}''' % (friendlyName, self.AppId)
        data = ''
        req.data = body.encode()
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 發送模板短信
    # @param to  必選參數     短信接收彿手機號碼集合,用英文逗號分開
    # @param datas 可選參數    內容數據
    # @param tempId 必選參數    模板Id
    def sendTemplateSMS(self, to, datas, tempId):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SMS/TemplateSMS?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        # auth = base64.encodestring(src).strip()
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)
        # 建立包體
        b = ''
        for a in datas:
            b += '<data>%s</data>' % (a)

        body = '<?xml version="1.0" encoding="utf-8"?><SubAccount><datas>' + b + '</datas><to>%s</to><templateId>%s</templateId><appId>%s</appId>\
                </SubAccount>\
                ' % (to, tempId, self.AppId)
        if self.BodyType == 'json':
            # if this model is Json ..then do next code
            b = '['
            for a in datas:
                b += '"%s",' % (a)
            b += ']'
            body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, tempId, self.AppId)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 外呼通知
    # @param to 必選參數    被叫號碼
    # @param mediaName 可選參數    語音文件名稱,格式 wav。與mediaTxt不能同時爲空。當不爲空時mediaTxt屬性失效。
    # @param mediaTxt 可選參數    文本內容
    # @param displayNum 可選參數    顯示的主叫號碼
    # @param playTimes 可選參數    循環播放次數,1-3次,默認播放1次。
    # @param respUrl 可選參數    外呼通知狀態通知回調地址,雲通信平臺將向該Url地址發送呼叫結果通知。
    # @param userData 可選參數    用戶私有數據
    # @param maxCallTime 可選參數    最大通話時長
    # @param speed 可選參數    發音速度
    # @param volume 可選參數    音量
    # @param pitch 可選參數    音調
    # @param bgsound 可選參數    背景音編號

    def landingCall(self, to, mediaName, mediaTxt, displayNum, playTimes, respUrl, userData, maxCallTime, speed, volume,
                    pitch, bgsound):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/Calls/LandingCalls?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        # auth = base64.encodestring(src).strip()
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?><LandingCall>\
                <to>%s</to><mediaName>%s</mediaName><mediaTxt>%s</mediaTxt><appId>%s</appId><displayNum>%s</displayNum>\
                <playTimes>%s</playTimes><respUrl>%s</respUrl><userData>%s</userData><maxCallTime>%s</maxCallTime><speed>%s</speed>
                <volume>%s</volume><pitch>%s</pitch><bgsound>%s</bgsound></LandingCall>\
                ''' % (
            to, mediaName, mediaTxt, self.AppId, displayNum, playTimes, respUrl, userData, maxCallTime, speed, volume,
            pitch, bgsound)
        if self.BodyType == 'json':
            body = '''{"to": "%s", "mediaName": "%s","mediaTxt": "%s","appId": "%s","displayNum": "%s","playTimes": "%s","respUrl": "%s","userData": "%s","maxCallTime": "%s","speed": "%s","volume": "%s","pitch": "%s","bgsound": "%s"}''' % (
                to, mediaName, mediaTxt, self.AppId, displayNum, playTimes, respUrl, userData, maxCallTime, speed,
                volume,
                pitch, bgsound)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 語音驗證碼
    # @param verifyCode  必選參數   驗證碼內容,爲數字和英文字母,不區分大小寫,長度4-8位
    # @param playTimes  可選參數   播放次數,1-3次
    # @param to 必選參數    接收號碼
    # @param displayNum 可選參數    顯示的主叫號碼
    # @param respUrl 可選參數    語音驗證碼狀態通知回調地址,雲通信平臺將向該Url地址發送呼叫結果通知
    # @param lang 可選參數    語言類型
    # @param userData 可選參數    第三方私有數據

    def voiceVerify(self, verifyCode, playTimes, to, displayNum, respUrl, lang, userData):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/Calls/VoiceVerify?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        # auth = base64.encodestring(src).strip()
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)

        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?><VoiceVerify>\
                <appId>%s</appId><verifyCode>%s</verifyCode><playTimes>%s</playTimes><to>%s</to><respUrl>%s</respUrl>\
                <displayNum>%s</displayNum><lang>%s</lang><userData>%s</userData></VoiceVerify>\
                ''' % (self.AppId, verifyCode, playTimes, to, respUrl, displayNum, lang, userData)
        if self.BodyType == 'json':
            # if this model is Json ..then do next code
            body = '''{"appId": "%s", "verifyCode": "%s","playTimes": "%s","to": "%s","respUrl": "%s","displayNum": "%s","lang": "%s","userData": "%s"}''' % (
                self.AppId, verifyCode, playTimes, to, respUrl, displayNum, lang, userData)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # IVR外呼
    # @param number  必選參數     待呼叫號碼,爲Dial節點的屬性
    # @param userdata 可選參數    用戶數據,在<startservice>通知中返回,只容許填寫數字字符,爲Dial節點的屬性
    # @param record   可選參數    是否錄音,可填項爲true和false,默認值爲false不錄音,爲Dial節點的屬性

    def ivrDial(self, number, userdata, record):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch;
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/ivr/dial?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        req.add_header("Accept", "application/xml")
        req.add_header("Content-Type", "application/xml;charset=utf-8")
        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?>
                    <Request>
                        <Appid>%s</Appid>
                        <Dial number="%s"  userdata="%s" record="%s"></Dial>
                    </Request>
                ''' % (self.AppId, number, userdata, record)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()
            xtj = xmltojson()
            locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 話單下載
    # @param date   必選參數    day 表明前一天的數據(從00:00 – 23:59),目前只支持按天查詢
    # @param keywords  可選參數     客戶的查詢條件,由客戶自行定義並提供給雲通信平臺。默認不填忽略此參數
    def billRecords(self, date, keywords):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/BillRecords?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?><BillRecords>\
                <appId>%s</appId><date>%s</date><keywords>%s</keywords>\
                </BillRecords>\
                ''' % (self.AppId, date, keywords)
        if self.BodyType == 'json':
            # if this model is Json ..then do next code
            body = '''{"appId": "%s", "date": "%s","keywords": "%s"}''' % (self.AppId, date, keywords)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()

            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 主賬號信息查詢

    def queryAccountInfo(self):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/AccountInfo?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        body = ''
        req.add_header("Authorization", auth)
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 短信模板查詢
    # @param templateId  必選參數   模板Id,不帶此參數查詢所有可用模板

    def QuerySMSTemplate(self, templateId):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SMS/QuerySMSTemplate?sig=" + sig
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)

        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?><Request>\
                <appId>%s</appId><templateId>%s</templateId></Request>
                ''' % (self.AppId, templateId)
        if self.BodyType == 'json':
            # if this model is Json ..then do next code
            body = '''{"appId": "%s", "templateId": "%s"}''' % (self.AppId, templateId)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main2(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 呼叫結果查詢
    # @param callsid   必選參數    呼叫ID

    def CallResult(self, callSid):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/CallResult?sig=" + sig + "&callsid=" + callSid
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        body = ''
        req.add_header("Authorization", auth)
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()
            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 呼叫狀態查詢
    # @param callid   必選參數    一個由32個字符組成的電話惟一標識符
    # @param action      可選參數     查詢結果通知的回調url地址
    def QueryCallState(self, callid, action):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/ivr/call?sig=" + sig + "&callid=" + callid
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        self.setHttpHeader(req)
        req.add_header("Authorization", auth)

        # 建立包體
        body = '''<?xml version="1.0" encoding="utf-8"?><Request>\
                <Appid>%s</Appid><QueryCallState callid="%s" action="%s"/>\
                </Request>\
                ''' % (self.AppId, callid, action)
        if self.BodyType == 'json':
            # if this model is Json ..then do next code
            body = '''{"Appid":"%s","QueryCallState":{"callid":"%s","action":"%s"}}''' % (self.AppId, callid, action)
        req.data = body.encode()
        data = ''
        try:
            res = urllib2.urlopen(req)
            data = res.read()

            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 語音文件上傳
    # @param filename   必選參數    文件名
    # @param body      必選參數     二進制串
    def MediaFileUpload(self, filename, body):

        self.accAuth()
        nowdate = datetime.datetime.now()
        self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
        # 生成sig
        signature = self.AccountSid + self.AccountToken + self.Batch
        sig = md5(signature.encode()).hexdigest().upper()
        # 拼接URL
        url = "https://" + self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/Calls/MediaFileUpload?sig=" + sig + "&appid=" + self.AppId + "&filename=" + filename
        # 生成auth
        src = self.AccountSid + ":" + self.Batch
        auth = base64.encodebytes(src.encode()).decode().strip()
        req = urllib2.Request(url)
        req.add_header("Authorization", auth)
        if self.BodyType == 'json':
            req.add_header("Accept", "application/json")
            req.add_header("Content-Type", "application/octet-stream")

        else:
            req.add_header("Accept", "application/xml")
            req.add_header("Content-Type", "application/octet-stream")

        # 建立包體
        req.data = body.encode()

        try:
            res = urllib2.urlopen(req)
            data = res.read()

            res.close()

            if self.BodyType == 'json':
                # json格式
                locations = json.loads(data)
            else:
                # xml格式
                xtj = xmltojson()
                locations = xtj.main(data)
            if self.Iflog:
                self.log(url, body, data)
            return locations
        except Exception as error:
            if self.Iflog:
                self.log(url, body, data)
            return {'172001': '網絡錯誤'}

    # 子賬號鑑權
    def subAuth(self):
        if (self.ServerIP == ""):
            print('172004')
            print('IP爲空')

        if (int(self.ServerPort) <= 0):
            print('172005')
            print('端口錯誤(小於等於0)')

        if (self.SoftVersion == ""):
            print('172013')
            print('版本號爲空')

        if (self.SubAccountSid == ""):
            print('172008')
            print('子賬號爲空')

        if (self.SubAccountToken == ""):
            print('172009')
            print('子賬號令牌爲空')

        if (self.AppId == ""):
            print('172012')
            print('應用ID爲空')

    # 主賬號鑑權
    def accAuth(self):
        if (self.ServerIP == ""):
            print('172004')
            print('IP爲空')

        if (int(self.ServerPort) <= 0):
            print('172005')
            print('端口錯誤(小於等於0)')

        if (self.SoftVersion == ""):
            print('172013')
            print('版本號爲空')

        if (self.AccountSid == ""):
            print('172006')
            print('主賬號爲空')

        if (self.AccountToken == ""):
            print('172007')
            print('主賬號令牌爲空')

        if (self.AppId == ""):
            print('172012')
            print('應用ID爲空')

    # 設置包頭
    def setHttpHeader(self, req):
        if self.BodyType == 'json':
            req.add_header("Accept", "application/json")
            req.add_header("Content-Type", "application/json;charset=utf-8")

        else:
            req.add_header("Accept", "application/xml")
            req.add_header("Content-Type", "application/xml;charset=utf-8")
CCPRestSDK修改後的代碼
from .CCPRestSDK import REST
from django.conf import settings
# 注:在配置文件dev中完成四個配置信息
# 說明:主帳號,登錄雲通信網站後,可在"控制檯-應用"中看到開發者主帳號ACCOUNT SID
_accountSid = settings.SMS_ACCOUNTSID
# 說明:主帳號Token,登錄雲通信網站後,可在控制檯-應用中看到開發者主帳號AUTH TOKEN
_accountToken = settings.SMS_ACCOUNTTOKEN
# 說明:請使用管理控制檯首頁的APPID或本身建立應用的APPID
_appId = settings.SMS_APPID
# 說明:請求地址,生產環境配置成app.cloopen.com,開發環境配置成sandboxapp.cloopen.com
_serverIP = settings.SMS_SERVERIP

# 說明:請求端口 ,生產環境爲8883
_serverPort = "8883"
# 說明:REST API版本號保持不變
_softVersion = '2013-12-26'

def send_sms(mobile, code_expire_tuple, temp_id):
    # 配置
    rest = REST(_serverIP, _serverPort, _softVersion)
    rest.setAccount(_accountSid, _accountToken)
    rest.setAppId(_appId)
    # 發送
    result = rest.sendTemplateSMS(mobile, code_expire_tuple, temp_id)
    # 結果:信息成功發生,結果字典result中 statuCode 字段爲 "000000"
    if result.get("statusCode") == "000000":
        return True  # 表示發送短信成功
    else:
        return False  # 表示發送失敗
sms.py代碼
相關文章
相關標籤/搜索