tool.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #coding=utf-8
  2. from django.conf import settings
  3. from django.contrib.auth import get_user_model
  4. from util.wx.wechat import WeChat
  5. from util.wx.WXBizDataCrypt import WXBizDataCrypt
  6. from apps.exceptions import CustomError
  7. from apps.activity.models import Activity
  8. from apps.WechatApplet.models import WechatApplet
  9. from apps.customer.models import Customer, CustomerWechat
  10. User = get_user_model()
  11. class WechatHandel(object):
  12. @staticmethod
  13. def login(code, appid, activity_id):
  14. app = WechatApplet.getByAppid(appid)
  15. if activity_id:
  16. activity = Activity.objects.filter(id=activity_id, delete=False, check_status=settings.PASS).first()
  17. if not activity:
  18. activity = Activity.objects.filter(delete=False, check_status=settings.PASS).order_by('-create_time').first()
  19. else:
  20. activity = Activity.objects.filter(delete=False, check_status=settings.PASS).order_by('-create_time').first()
  21. if not activity:
  22. raise CustomError(u'未找到活动!')
  23. res = WeChat.code2Session(appid, app.secret, code)
  24. instance = CustomerWechat.objects.filter(openid=res['openid'], branch=activity.branch).first()
  25. if not instance:
  26. instance = CustomerWechat.objects.create(
  27. branch=activity.branch,
  28. openid=res['openid'],
  29. session_key=res['session_key']
  30. )
  31. else:
  32. instance.session_key = res['session_key']
  33. instance.save()
  34. return instance, activity.id
  35. @staticmethod
  36. def bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id):
  37. WechatApplet.getByAppid(appid)
  38. activity = Activity.objects.filter(id=activity_id).first()
  39. if not activity:
  40. raise CustomError(u'未找到相应的活动')
  41. customer_wechat = CustomerWechat.objects.filter(openid=openid, branch=activity.branch).first()
  42. if not customer_wechat:
  43. raise CustomError(u'未找到相应的微信客户!')
  44. pc = WXBizDataCrypt(appid, customer_wechat.session_key)
  45. phon_data = pc.decrypt(phoneEncryptedData, phoneIv)
  46. tel = phon_data['purePhoneNumber']
  47. if customer_wechat.customer:
  48. if customer_wechat.customer.user.username != tel:
  49. raise CustomError(u'微信绑定的手机号与系统记录的不符!')
  50. else:
  51. return customer_wechat.customer
  52. user = User.objects.filter(username=tel).first()
  53. if not user:
  54. user = User.objects.create_user(User.CUSTOMER, tel, password=tel, **{'name': tel, 'tel': tel})
  55. customer = Customer.objects.filter(branch=customer_wechat.branch, user=user).first()
  56. if not customer:
  57. customer = Customer.objects.create(branch=customer_wechat.branch, user=user, name=tel, tel=tel)
  58. customer_wechat.customer = customer
  59. customer_wechat.save()
  60. return customer