## -*- coding: utf-8 -*- # !/usr/bin/env python import logging import random import time from collections import OrderedDict import simplejson as json from alibabacloud_imarketing20220704.client import Client from alibabacloud_imarketing20220704.models import CreateDeviceRequest, ListAdvertisingRequestApp, \ ListAdvertisingRequestImp, ListAdvertisingRequestUser, ListAdvertisingRequest, GetUserFinishedAdRequest from alibabacloud_tea_openapi.models import Config from aliyunsdkafs.request.v20180112 import AuthenticateSigRequest from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest from aliyunsdkunimkt.request.v20181207 import PopUpQueryRequest, QueryPromotionRequest from aliyunsdkunimkt.request.v20181212 import QueryUnionPromotionRequest, GetUnionTaskStatusRequest, \ RegistDeviceRequest from django.conf import settings from requests import ConnectionError from simplejson import JSONDecodeError from typing import Union from apps.web.constant import Const logger = logging.getLogger(__name__) def create_sign(map, key): # type: (dict, Union[str, None]) -> str SECRET = "1234512345123451" sign = '' # 1 TODO 校验map,并排序 Odict = OrderedDict(dict(sorted(map.items()))) # 2 TODO 拼接字符串 sign = '' for k, v in Odict.items(): sign += str(k) sign += str(v) # 3 TODO 加盐 sign = SECRET + sign + SECRET ba = bytearray(sign) # 4 TODO MD5加密 import hashlib sign = hashlib.md5(ba).hexdigest().upper() return sign class Aliyun(object): def __init__(self, appid, secret, region_id, product_code, endpoint): self.client = AcsClient(appid, secret) self.client.add_endpoint(region_id, product_code, endpoint) @staticmethod def create_sign(map, key): # type: (dict, Union[str, None]) -> str SECRET = "1234512345123451" sign = '' # 1 TODO 校验map,并排序 Odict = OrderedDict(dict(sorted(map.items()))) # 2 TODO 拼接字符串 sign = '' for k, v in Odict.items(): sign += str(k) sign += str(v) # 3 TODO 加盐 sign = SECRET + sign + SECRET ba = bytearray(sign) # 4 TODO MD5加密 import hashlib sign = hashlib.md5(ba).hexdigest().upper() return sign @staticmethod def first_Cap(string): return string[0].upper() + string[1:] class AliyunSlider(Aliyun): def __init__(self, appid = Const.ALI_SLIDER_ACCESSKEY_ID, secret = Const.ALI_SLIDER_ACCESSKEY_SECRET): super(AliyunSlider, self).__init__( appid = appid, secret = secret, region_id = 'cn-hangzhou', product_code = 'afs', endpoint = 'afs.aliyuncs.com') def check_validation_results(self, sessionId, sig, token): request = AuthenticateSigRequest.AuthenticateSigRequest() # 会话ID。必填参数,从前端获取,不可更改。 request.set_SessionId(sessionId) # 签名串。必填参数,从前端获取,不可更改。 request.set_Sig(sig) # 请求唯一标识。必填参数,从前端获取,不可更改。 request.set_Token(token) # 场景标识。必填参数,从前端获取,不可更改。 request.set_Scene('nc_message_h5') # 应用类型标识。必填参数,后端填写。 request.set_AppKey('FFFF0N000000000088F1') # 客户端IP。必填参数,后端填写。 request.set_RemoteIp('120.26.227.50') result = self.client.do_action_with_exception(request) # 返回code 100表示验签通过,900表示验签失败 return result class AliLaXin(Aliyun): def __init__(self, appid=settings.ALIYUN_ACCESS_KEY_ID, secret=settings.ALIYUN_ACCESS_KEY_SECRET): super(AliLaXin, self).__init__( appid=appid, secret=secret, region_id='cn-hangzhou', product_code='UniMkt', endpoint='cloudcode.aliyuncs.com') def QueryUnionPromotionRequest(self, param): """ :param param: {'alipayOpenId': '2088812351147125','channelId': 'test',} :return: """ request = QueryUnionPromotionRequest.QueryUnionPromotionRequest() request.set_AlipayOpenId(param.get('alipayOpenId')) request.set_ChannelId(param.get('channelId') or settings.ALIPAY_LAXIN_CHANNEL_ID) sign_dict = { 'alipayOpenId': request.get_AlipayOpenId(), 'channelId': request.get_ChannelId() } sign = self.create_sign(sign_dict, None) request.set_Sign(sign) try: resp = self.client.do_action_with_exception(request) except: return {} return json.loads(resp) def GetUnionTaskStatusRequest(self, param): """ :param param: {'alipayOpenId': '小明','taskId': '1623913226986034',} :return: """ request = GetUnionTaskStatusRequest.GetUnionTaskStatusRequest() request.set_AlipayOpenId(param.get('alipayOpenId')) request.set_TaskId(param.get('taskId')) request.add_query_param('ChannelId', param.get('channelId', settings.ALIPAY_LAXIN_CHANNEL_ID)) # 此字段不参与签名 sign_dict = { 'alipayOpenId': request.get_AlipayOpenId(), 'taskId': request.get_TaskId(), } sign = create_sign(sign_dict, None) request.set_Sign(sign) try: resp = self.client.do_action_with_exception(request) except: return {} return json.loads(resp) class AliRuHui(Aliyun): def __init__(self, appid=settings.ALIYUN_ACCESS_KEY_ID, secret=settings.ALIYUN_ACCESS_KEY_SECRET): super(AliRuHui, self).__init__( appid=appid, secret=secret, region_id='cn-hangzhou', product_code='UniMkt', endpoint='cloudcode.cn-hangzhou.aliyuncs.com') # 入会 def PopUpQueryRequest(self, param): request = PopUpQueryRequest.PopUpQueryRequest() request.set_UrlId(param.get('urlId')) # url Id号码 request.set_ChannelId(param.get('channelId', settings.ALIPAY_RUHUI_CHANNEL_ID)) # 渠道号 request.set_AlipayOpenId(param.get('alipayOpenId')) # 阿里 openId request.set_OuterCode(param.get('outerCode')) # 设备号 request.set_Extra(param.get('extra', '')) # 额外字段 request.set_OptionType('1') # 渠道商自由分配 !!! 重要 try: resp = self.client.do_action_with_exception(request) except: return {} return json.loads(resp) def QueryPromotionRequest(self, param): request = QueryPromotionRequest.QueryPromotionRequest() request.set_AlipayOpenId(param.get('alipayOpenId')) # 阿里 openId request.set_ChannelId(param.get('channelId', settings.ALIPAY_RUHUI_CHANNEL_ID)) # 渠道号 try: resp = self.client.do_action_with_exception(request) except: return {} return json.loads(resp) def RegistDeviceRequest(self): request = RegistDeviceRequest.RegistDeviceRequest() # 固定值 request.set_FirstScene('社区') request.set_SecondScene('普通社区') request.set_DeviceType('聚合支付') request.set_ChannelId('QD-VHWFTEST-434497') # 设备唯一编号 request.set_OuterCode('434497') # 设置省份 request.set_Province('山东省') # 设置所属城市 request.set_City('济南') # 设置所属区域 request.set_District('高新区') # 设置详细地址 request.set_DetailAddr('中铁财智6号楼') # 设备型号 request.set_DeviceModelNumber('设备型号') # 设备名称 request.set_DeviceName('猛犸充电桩') # 设备点位名称 request.set_LocationName('点位名称') # 楼层名称 request.set_Floor('楼层') resp = self.client.do_action_with_exception(request) return resp class AliSms(Aliyun): def __init__(self, appid = 'LTAI4GEc1j8pvs4EjFrtL5K9', secret = 'KuCEo8YWRn7tjQaJsXJCcG7P4leBMr'): super(AliSms, self).__init__( appid = appid, secret = secret, region_id = 'cn-hangzhou', product_code = 'Dysmsapi', endpoint = 'dysmsapi.aliyuncs.com') def send(self, phoneNumber, templateId, msg, productName, verifyCode = False): """ :param phoneNumber: :param templateId: :param msg: :param productName: :return: dict """ try: request = CommonRequest() request.set_accept_format('json') request.set_method('POST') request.set_protocol_type('http') # https | http request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('RegionId', 'cn-hangzhou') request.add_query_param('PhoneNumbers', phoneNumber) # request.add_query_param('SignName', productName) request.add_query_param('SignName', u'微付乐') request.add_query_param('TemplateCode', templateId) if verifyCode: request.add_query_param('TemplateParam', {'code': msg}) else: request.add_query_param('TemplateParam', {'user': productName, 'detail': msg}) response = self.client.do_action_with_exception(request) result = json.loads(response) if result['Code'] == 'OK': return {'result': True, 'msg': 'success'} else: return {'result': False, 'msg': result['Message']} except JSONDecodeError as e: logger.exception(e) return {'result': False, 'msg': u'短信服务器繁忙,请稍后重试'} except ConnectionError as e: logger.exception(e) return {'result': False, 'msg': u'短信服务器不可用,请稍后重试'} class AlipayYunMaV3: def __init__(self, access_key_id=None, access_key_secret=None): self.config = Config( access_key_id=access_key_id or settings.ALIYUN_ACCESS_KEY_ID, access_key_secret=access_key_secret or settings.ALIYUN_ACCESS_KEY_SECRET, region_id='cn-hangzhou', ) def reg_dev(self, dic): self.config.endpoint = 'imarketing.cn-zhangjiakou.aliyuncs.com' dic.update({ 'channel_id': settings.ALIPAY_CHANNEL_ID_V3, 'media_id': settings.ALIPAY_MEDIA_ID_V3, }) request = CreateDeviceRequest(**dic) client = Client(self.config) response = client.create_device(request) return response def get_cpm_body(self, openId, logicalCode): cpm_imp_id = 'CPM{:}{:03d}'.format(int(time.time() * 1000), random.randint(1, 1000)) self.config.endpoint = 'imarketing.aliyuncs.com' app = ListAdvertisingRequestApp(mediaid=settings.ALIPAY_MEDIA_ID_V3, sn=logicalCode) cpm_imp = ListAdvertisingRequestImp(id=cpm_imp_id, tagid=settings.ALIPAY_IMP_CPM_V3) user = ListAdvertisingRequestUser(id=openId, usertype='ALIPAY_OPEN_ID') request = ListAdvertisingRequest(app=app, imp=[cpm_imp], user=user) client = Client(self.config) response = client.list_advertising(request) return response def get_cpa_ruhui_body(self, openId, logicalCode): rh_imp_id = 'CPARH{:}{:03d}'.format(int(time.time() * 1000), random.randint(1, 1000)) self.config.endpoint = 'imarketing.aliyuncs.com' app = ListAdvertisingRequestApp(mediaid=settings.ALIPAY_MEDIA_ID_V3, sn=logicalCode) rh_imp = ListAdvertisingRequestImp(id=rh_imp_id, tagid=settings.ALIPAY_IMP_CPA_RUHUI_V3) user = ListAdvertisingRequestUser(id=openId, usertype='ALIPAY_OPEN_ID') request = ListAdvertisingRequest(app=app, imp=[rh_imp], user=user, id=rh_imp_id) client = Client(self.config) response = client.list_advertising(request) return response def get_cpa_laxin_body(self, openId, logicalCode): lx_imp_id = 'CPALX{:}{:03d}'.format(int(time.time() * 1000), random.randint(1, 1000)) self.config.endpoint = 'imarketing.aliyuncs.com' app = ListAdvertisingRequestApp(mediaid=settings.ALIPAY_MEDIA_ID_V3, sn=logicalCode) lx_imp = ListAdvertisingRequestImp(id=lx_imp_id, tagid=settings.ALIPAY_IMP_CPA_RUHUI_V3) user = ListAdvertisingRequestUser(id=openId, usertype='ALIPAY_OPEN_ID') request = ListAdvertisingRequest(app=app, imp=[lx_imp], user=user, id=lx_imp_id) client = Client(self.config) response = client.list_advertising(request) return response def query_task_status(self, clicklink, openId, adid, taskType='RH'): self.config.endpoint = 'imarketing.aliyuncs.com' if taskType == 'RH': # 入会 tagid = settings.ALIPAY_IMP_CPA_RUHUI_V3 elif taskType == 'LX': # 拉新 tagid = settings.ALIPAY_IMP_CPA_LAXIN_V3 elif taskType == 'CPM': tagid = settings.ALIPAY_IMP_CPM_V3 else: raise TypeError('task type not in ["CPM", "RH", "LX"]') request = GetUserFinishedAdRequest(adid=adid, clicklink=clicklink, mediaid=settings.ALIPAY_MEDIA_ID_V3, tagid=tagid, uid=openId) client = Client(self.config) response = client.get_user_finished_ad(request) return response