1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- #coding=utf-8
- from django.conf import settings
- from django.contrib.auth import get_user_model
- from util.wx.wechat import WeChat
- from util.wx.WXBizDataCrypt import WXBizDataCrypt
- from apps.exceptions import CustomError
- from apps.activity.models import Activity
- from apps.customer.models import Customer, CustomerWechat
- User = get_user_model()
- class WechatHandel(object):
- @staticmethod
- def login(code, appid, activity_id):
- WeChat.checkAppid(appid)
- if activity_id:
- activity = Activity.objects.filter(id=activity_id, enabled=True, delete=False).first()
- if not activity:
- activity = Activity.objects.filter().order_by('-create_time').first()
- else:
- activity = Activity.objects.filter().order_by('-create_time').first()
- res = WeChat.code2Session(appid, settings.SECRET, code)
- instance = CustomerWechat.objects.filter(openid=res['openid'], branch=activity.branch).first()
- if not instance:
- instance = CustomerWechat.objects.create(
- branch=activity.branch,
- openid=res['openid'],
- session_key=res['session_key']
- )
- else:
- instance.session_key = res['session_key']
- instance.save()
- return instance, activity.id
- @staticmethod
- def bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id):
- WeChat.checkAppid(appid)
- activity = Activity.objects.filter(id=activity_id, enabled=True, delete=False).first()
- if not activity:
- raise CustomError(u'未找到相应的活动')
- customer_wechat = CustomerWechat.objects.filter(openid=openid, branch=activity.branch).first()
- if not customer_wechat:
- raise CustomError(u'未找到相应的微信客户!')
- pc = WXBizDataCrypt(settings.APPID, customer_wechat.session_key)
- phon_data = pc.decrypt(phoneEncryptedData, phoneIv)
- tel = phon_data['purePhoneNumber']
- if customer_wechat.customer:
- if customer_wechat.customer.user.username != tel:
- raise CustomError(u'微信绑定的手机号与系统记录的不符!')
- else:
- return customer_wechat.customer
- user = User.objects.filter(username=tel).first()
- if not user:
- user = User.objects.create_user(User.CUSTOMER, tel, password=tel, **{'name': tel, 'tel': tel})
- customer = Customer.objects.filter(branch=customer_wechat.branch, user=user).first()
- if not customer:
- customer = Customer.objects.create(branch=customer_wechat.branch, user=user, name=tel, tel=tel)
- customer_wechat.customer = customer
- customer_wechat.save()
- return customer
|