Beispiel #1
0
def sendSMS(tel,code):
# TODO: sending SMS for register
# 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient(yunpian_apikey)
    param = {YC.MOBILE:tel,YC.TEXT:'【云片网】您的验证码是{0}'.format(code)}
    r = clnt.sms().single_send(param)
    return r
Beispiel #2
0
    def post(self, request, *args, **kwargs):
        msg = Resphonse_msg()
        pho = PhoneForms(request.data)
        if pho.is_valid():
            pass_values = pho.clean()
            ran_str = ''.join(random.sample(string.digits, 4))
            try:
                pass_values["code"] = ran_str
                models.Phone_code.objects.update_or_create(
                    phone=pass_values["phone"],
                    defaults={"code": pass_values["code"]})
            except Exception as e:
                msg.error = "系统错误"
                msg.status = False
                return Response(msg.__dict__)
            else:
                # 手机短信发送

                clnt = YunpianClient("e8c2bea168255f72a413f04c2f6393d3")
                # 次字符串在账号后台可以得到
                param = {
                    YC.MOBILE: pass_values["phone"],
                    YC.TEXT: "【天心软件】您的验证码是%s" % (ran_str)
                }
                r = clnt.sms().single_send(param)
                print(msg.__dict__)
        else:
            msg.status = False
            msg.error = pho.errors

        return Response(msg.__dict__)
Beispiel #3
0
 def send_sms(self, code, mobile):
     clnt = YunpianClient(self.api_key)
     parmas = {
         YC.MOBILE: mobile,
         YC.TEXT: "您的验证码是{code}。如非本人操作,请忽略本短信".format(code=code),
     }
     res = clnt.sms().single_send(parmas)
     return res
Beispiel #4
0
def send_by_yunpian(to, content):
    logging.info('sending sms by yunpian to :{} content: {}'.format(to, content))

    clnt = YunpianClient(apikey=api_key)
    param = {YC.MOBILE: to, YC.TEXT: content}
    r = clnt.sms().single_send(param)
    logging.info(
        'sending sms {} result: {} {}, {}, {}, {}'.format(to, r.code(), r.msg(), r.data(), r.detail(), r.exception()))
Beispiel #5
0
    def _init(self):
        """扩展父类配置加载"""

        super(YunPianSmsService, self)._init()
        self.api_key = self.sms_config['ak']
        if not self.api_key:
            raise SmsException(_(u'接口验证序号不存在'))
        self.client = YunpianClient(self.api_key)
Beispiel #6
0
def send_mobile_msg(mobile, code):
    # 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient('e8abe129a4e9f9a7c8c9adc8ece9ebc9')
    param = {YC.MOBILE: mobile, YC.TEXT: '【御城领】您的验证码是{}'.format(code)}
    r = clnt.sms().single_send(param)
    print(r.data())
    print(r.msg())
    return r.code()
Beispiel #7
0
def send_phone_msg(telephone, code):
    # 初始化client,apikey作为所有请求的默认值
    # clnt = YunpianClient('70b0eb56669841bbecff6c000c99d7e7')                                 # API key是云片账号中绑定的私有的
    clnt = YunpianClient(
        'e8abe129a4e9f9a7c8c9adc8ece9ebc9')  # API key是云片账号中绑定的私有的

    param = {YC.MOBILE: telephone, YC.TEXT: '【于成令】您的验证码是{}'.format(code)}
    r = clnt.sms().single_send(param)
    return r.code()  # 返回发送状态码
Beispiel #8
0
def yunpian_send_code(code, phone_num):
    from yunpian_python_sdk.model import constant as YC
    from yunpian_python_sdk.ypclient import YunpianClient

    # 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient('6e3b47b00f792b1067d05a921b1c1d33')
    param = {YC.MOBILE: phone_num, YC.TEXT: f'【万人圆梦】您的验证码是{code}'}
    r = clnt.sms().single_send(param)
    return r.code()
Beispiel #9
0
def send_mobile_msg(mobile, code):
    # 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient(YP_API)
    param = {
        YC.MOBILE: mobile,
        YC.TEXT: '【Python进化讲堂】欢迎您注册熊熊论坛,验证码:{}(5分钟内有效,如非本人操作,请忽略)'.format(code)
    }
    r = clnt.sms().single_send(param)
    print(r.code(), r.msg(), r.data())
    return r.code()
Beispiel #10
0
def send_msg(phone, msg):
    # 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient(options.sms_api_key)
    param = {YC.MOBILE: phone, YC.TEXT: msg}
    result = clnt.sms().single_send(param)
    if result.code() != 0:
        msg = "Error send msg to phone <{0}>".format(phone)
        LOG.exception(msg)
        return False
    return True
Beispiel #11
0
    def one(self):
        client = YunpianClient(apikey=self.apikey)
        # TODO: 单发
        # 初始化client, apikey作为所有请求的默认值
        tpl_value = urllib.parse.urlencode({'#vip_type#': self.vip_type, '#consumption_amount#': self.consumption_amount})   # 注意此处不要用sdk中的解码方法,超级傻逼
        # code 和 app是你模版里面的变量,我们使用py3的urllib.parse.urlencode方法对此参数进行转码,注意在{}中,需要在模版变量前后加上#,不然会返回参数不正确
        param = {YC.MOBILE: self.mobile, YC.TPL_ID: '3256576', YC.TPL_VALUE: tpl_value}
        r = client.sms().tpl_single_send(param)
        # print(r.msg())

        return r.msg()
Beispiel #12
0
def phone(request):
    a = request.GET.get('id')
    print(a)
    ma = id_generator()
    request.session['phone'] = ma

    clnt = YunpianClient('1f72317602ff1631e5b889358d107603')
    param = {YC.MOBILE: '' + str(a) + '', YC.TEXT: '您的验证码是' + ma + ''}
    r = clnt.sms().single_send(param)

    return HttpResponse(123)
Beispiel #13
0
def send_security_code(mobile, security_code, securtity_name):
    # 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient(apikey)
    print(TEMPLATES[securtity_name] % (security_code))
    param = {
        YC.MOBILE: mobile,
        YC.TEXT: TEMPLATES[securtity_name] % (security_code)
    }
    r = clnt.sms().single_send(param)
    print(r.code(), r.data(), r.msg())
    if r.code() != 0:
        raise Exception("验证码发送失败!")
Beispiel #14
0
def send_verify_code(request, phone):
    # todo 判断接口的请求评论 防止有人频繁调用接口短信轰炸
    number = random.randint(1000, 9999)
    client = YunpianClient(apikey='2e1da426087927fcefc313d08536584b')
    tpl_value = urllib.parse.urlencode({'#code#': str(number)})
    param = {YC.MOBILE: phone, YC.TPL_ID: 2442232, YC.TPL_VALUE: tpl_value}
    r = client.sms().tpl_single_send(param)
    if r.code() == 0:
        cache.set('%s%s' % (request.session.session_key, "SESSION_KEY_NUMBER"), number, 3600 * 24)
        cache.set(request.session.session_key, phone, 3600 * 24)
        return r.code()
    return r.code()
Beispiel #15
0
def send_verification_code(verification_code, mobile):
    """
        发送短信验证码
    """
    client = YunpianClient(apikey=settings.YP_APIKEY)
    tpl_value = urllib.parse.urlencode({'#code#': verification_code})
    param = {
        YC.MOBILE: mobile,
        YC.TPL_ID: settings.YP_TPL_ID,
        YC.TPL_VALUE: tpl_value
    }
    r = client.sms().tpl_single_send(param)
    assert r.code() == 0
Beispiel #16
0
def send_sms(mobile, password):
    client = YunpianClient(apikey=API_KEY)
    tpl_value = urllib.parse.urlencode({
        '#domain#': 'http://baas.cnfoodchain.com',
        '#password#': password
    })  # 注意此处不要用sdk中的解码方法,超级傻逼
    param = {
        YC.MOBILE: mobile,
        YC.TPL_ID: TEMPLATE_ID,
        YC.TPL_VALUE: tpl_value
    }
    result = client.sms().tpl_single_send(param)
    return result
Beispiel #17
0
 def send_sms(self):
     # 初始化client,apikey作为所有请求的默认值
     clnt = YunpianClient(self.apikey)
     # 自己定义的短信内容,但要和后台模板相匹配才行
     # param = {YC.MOBILE: self.mobile, YC.TEXT: self.text}
     # r = clnt.sms().single_send(param)
     param = {
         YC.MOBILE: self.mobile,
         YC.TPL_ID: '2789228',
         YC.TPL_VALUE: '#code#=%s' % self.sms_code
     }
     r = clnt.sms().tpl_single_send(param)
     # print(r.code(), r.data(), r.msg())
     return r.msg()
Beispiel #18
0
def send_mobile_msg(mobile,code):
    clnt = YunpianClient('e8abe129a4e9f9a7c8c9adc8ece9ebc9')
    param = {YC.MOBILE:mobile,YC.TEXT:'【于成令】您的验证码是{}'.format(code)}
    r = clnt.sms().single_send(param)
    # 获取返回结果, 返回码:r.code(),返回码描述:r.msg(),API结果:r.data(),其他说明:r.detail(),调用异常:r.exception()
    # print(r.code())
    # print(r.msg())
    # print(r.data())
    return r.code()
    # 短信:clnt.sms() 账户:clnt.user() 签名:clnt.sign() 模版:clnt.tpl() 语音:clnt.voice() 流量:clnt.flow()

# if __name__ == '__main__':
#     status = send_mobile_msg(13714160953,1234)
#     print(status)
Beispiel #19
0
    def send(self):
        params = self.generate_params()

        client = YunpianClient(apikey=self._apikey)
        param = {
            YC.MOBILE: self._mobile,
            YC.TPL_ID: self._tplid,
            YC.TPL_VALUE: urllib.urlencode({"#code#": str(params[0])})
        }
        data = client.sms().tpl_single_send(param)
        print data.code()
        if data.code() == 0:
            return params
        return None
Beispiel #20
0
def yunpian_send_message(send_to, message):
    from yunpian_python_sdk.model import constant as YC
    from yunpian_python_sdk.ypclient import YunpianClient
    if not message or not send_to:
        print('没有通知老师,因为联系人为空')
        return
    # 初始化client,apikey作为所有请求的默认值
    clnt = YunpianClient('6e3b47b00f792b1067d05a921b1c1d33')
    param = {
        YC.MOBILE: str(send_to),
        YC.TEXT: message
    }
    r = clnt.sms().single_send(param)
    return r.code()
Beispiel #21
0
def changeTelephone(request):
    user_telephone = request.GET.get('user_telephone')
    if_registered = User.objects.filter(user_telephone=user_telephone).first()
    if not if_registered:
        clnt = YunpianClient('70b37503044891ec90e2b5da3f0a5fb1')
        auth_code = str(random.randint(100000, 999999))
        param = {YC.MOBILE: user_telephone, YC.TEXT: '【云片网】您的验证码是'+auth_code}
        r = clnt.sms().single_send(param)
        if r:
            return JsonResponse({'auth_code': auth_code, 'statuscode': '200'})
        else:
            return JsonResponse({'auth_code': auth_code, 'statuscode': '400'})
    else:
        return JsonResponse({'auth_code': '000000', 'statuscode': '400'})
Beispiel #22
0
class SMSToolKit:
    YP_API_CODE = os.getenv('YP_API_CODE')

    def __init__(self, apicode=None):
        apicode = apicode or self.YP_API_CODE or ''
        # 需要使用海外服务器
        self.client = YunpianClient(apicode,
                                    {YC.YP_SMS_HOST: "https://us.yunpian.com"})

    def send_sms(self, phone_number, message):
        """
        通过云片网发送短信        
        :param phone_number:
        :param message:
        :return:
        """

        # param = {YC.MOBILE: '18616020***', YC.TEXT: '【云片网】您的验证码是1234'}
        # param = {YC.MOBILE: urllib.parse.quote(phone_number), YC.TEXT: message}
        param = {YC.MOBILE: phone_number, YC.TEXT: message}
        r = self.client.sms().single_send(param)
        # 获取返回结果, 返回码:r.code(),返回码描述:r.msg(),API结果:r.data(),其他说明:r.detail(),调用异常:r.exception()
        # 短信:clnt.sms() 账户:clnt.user() 签名:clnt.sign() 模版:clnt.tpl() 语音:clnt.voice() 流量:clnt.flow()

        return r and r.code() == 0
Beispiel #23
0
    def _yunpian_sender(cls, number, message, tag):
        client = YunpianClient(SMS_YUNPIAN_APIKEY)
        param = {YC.MOBILE: number, YC.TEXT: message}
        r = client.sms().single_send(param)

        if r.code() == 200:
            r = r.json()
            code = r.get('code')
            # msg = r.get('msg')
            # sid = r.get('sid') or ''
            try:
                if int(code) == 0:
                    return True
            except Exception:
                return False
        return False
Beispiel #24
0
def message_validate(phone_number,validate_number):
	clnt = YunpianClient(Conf.YunPian_APIKEY)
	country = phone_number[0:3]
	if country == '+86':
		text = '%s%s%s' %('【1ShowRoom】您的验证码是',validate_number,'。如非本人操作,请忽略本短信')
	else:
		text = '%s%s' %('【1ShowRoom】Your 1ShowRoomOnline ID Verification Code is:',validate_number)
	# print country,text
	param = {YC.MOBILE:phone_number,YC.TEXT:text}
	r = clnt.sms().single_send(param)
	# r = r.code()
	# print r.code()
	if r.code() == 0:
		return True, r.msg()
	else:
		return False, r.msg()
Beispiel #25
0
class YunPianSMSHandler(object):
    def __init__(self, key, secret):
        self.key = key
        self.secret = secret
        self.client = YunpianClient(apikey=key)
        self.sender = self.client.sms()

    def send_with_template(self,
                           phone_number,
                           template_id,
                           template_params=None,
                           sms_sign=''):
        '''
        https://github.com/yunpian/yunpian-python-sdk
        https://www.jianshu.com/p/b2c1944c8b27
        '''
        template_params = template_params or {}
        if template_params:
            _params = {
                '#{}#'.format(key): value.encode('utf-8')
                for key, value in template_params.iteritems()
            }
            tpl_value = urllib.urlencode(_params)
        else:
            tpl_value = ''
        params = {
            YC.MOBILE: phone_number,
            YC.TPL_ID: int(template_id),
            YC.TPL_VALUE: tpl_value
        }
        result = self.sender.tpl_single_send(params)
        if result.code() != 0:
            raise exceptions.APISMSException(
                message=u'{}:{}'.format(result.code(), result.msg()))
        return result
Beispiel #26
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('country_code', type=str, location='json')
        parser.add_argument('mobile', required=True, type=str, location='json')
        parsed_args = parser.parse_args()

        # if not parsed_args['mobile']:  # 获取当前用户的手机号
        #     if parsed_args['token']:
        #         current_user = User.verify_auth_token(parsed_args['token'])
        #         if current_user is not None:
        #             parsed_args['mobile'] = current_user.mobile
        if not parsed_args['mobile']:
            abort(400, code=1000, message={'mobile': 'mobile is required'})

        country_code = parsed_args['country_code']
        if parsed_args['country_code']:
            if "+" not in parsed_args['country_code']:
                country_code = '+' + parsed_args['country_code']

        code = str(random.randint(100000, 999999))
        clnt = YunpianClient('71657fee075e49ecb6dea561fd321283')
        if not country_code or country_code == '+86':
            param = {
                YC.MOBILE: parsed_args['mobile'],
                YC.TEXT: '【腾达】您正在使用腾达,验证码:{}。请勿向任何人包括客服提供验证码。'.format(code)
            }

        else:
            param = {
                YC.MOBILE:
                country_code + parsed_args['mobile'],
                YC.TEXT:
                "【USDTex】Your verification code is:{}. Please don't leak it to anyone else."
                .format(code)
            }
        result = clnt.sms().single_send(param)
        if result.code() != 0:
            abort(400, code=1004, message={'err': result._msg})

        pin_code = SmsPinCode.query.get(parsed_args['mobile'])
        if pin_code is None:
            pin_code = SmsPinCode(id=parsed_args['mobile'])
        pin_code.generate_signature(code)

        return {}
Beispiel #27
0
    def run(self):
        mysql = self.mysql
        self.clnt = YunpianClient('304ab9c0aa24a69869052441f9afbe08')

        while True:
            try:
                rows = mysql.getAll("SELECT queue_id,msg, uid, tel, email FROM b_queue LIMIT 10")
                for row in rows:
                    queue_id, msg, uid, tel, email = row
                    print(msg)
                    r = self.sendtel_yunpian(tel, msg)
                    if r:
                        data = {'uid':uid, 'message': msg, 'send_time': int(time.time())}
                        mysql.insert('b_price_notify_log', data)
                        mysql.executeNonQuery("DELETE FROM b_queue WHERE queue_id=%s" % queue_id)
            except Exception as e:
                print(str(e))
            time.sleep(5)
        pass
Beispiel #28
0
    def __init__(self, conf, stone, logger, apikey):
        """
        conf 配置实例
        stone 存储实例
        :param conf:
        :param stone:
        """
        self._conf = conf
        self._stone = stone
        self._conn = pymssql.connect(self._conf.get('server', 'ip'), self._conf.get('server', 'user'),
                                     self._conf.get('server', 'password'),
                                     database=self._conf.get('server', 'database'))
        self._cur = self._conn.cursor()
        self._logger = logger
        self._templates = {}
        self._get_templates()
        self._clnt = YunpianClient(apikey)

        pass
Beispiel #29
0
 def sendsms(self):
     """发送短信"""
     now = time.strftime("%Y-%m-%d,%H:%M")
     message = now + ',' + self._message
     tpl_value = urllib.urlencode({"#msg#": message})
     clnt = YunpianClient(self._apikey)
     param = {
         YC.MOBILE: self._to_mobiles,
         YC.TPL_ID: self._tpl_id,
         YC.TPL_VALUE: tpl_value
     }
     try:
         r = clnt.sms().tpl_single_send(param)
         if r.code() == 0 and r.msg() == "发送成功":
             self.log("message send sucess".decode('gbk').encode('utf8'))
         else:
             self.log("message send fail:".decode('gbk').encode('utf8') +
                      r.msg())
     except:
         self.log("message send fail".decode('gbk').encode('utf8'))
Beispiel #30
0
    def post(self):
        from yunpian_python_sdk.model import constant as YC
        from yunpian_python_sdk.ypclient import YunpianClient
        import random

        # 获取手机号码
        mobile = self.get_argument('mobile')
        print(mobile)

        #生成随机四位数字
        moblie_code = ''
        for x in range(4):
            moblie_code += str(random.randint(0, 9))

        # 初始化client,apikey作为所有请求的默认值
        client = YunpianClient('78ccbe77a41da6a50c3da6a67d46b489')
        param = {YC.MOBILE: mobile, YC.TEXT: '【陈华征程】您的验证码是' + moblie_code}
        r = client.sms().single_send(param)
        #保存验证码到session中
        self.session['messagecode'] = moblie_code
        self.write('成功了')
Beispiel #31
0
def sms_send_price_gap(apikey,phones,content):
	for phone in phones:
		clnt = YunpianClient(apikey)
		param = {YC.MOBILE:phone,YC.TEXT:content}
		r = clnt.sms().single_send(param)