Пример #1
0
 def check_openid(self):
     if is_tourist():
         return TOKEN_ERROR
     state = request.args.to_dict().get('state')
     usid = request.user.id
     openid = get_model_return_dict(self.saccount.check_openid(usid))
     if not openid['openid']:
         response = {}
         response['message'] = u'执行跳转'
         response['status'] = 302
         data = {}
         update = {}
         state2 = get_random_str(10)
         update['state'] = state2
         result = self.suser.update_user_by_uid(usid, update)
         if not result:
             return SYSTEM_ERROR
         login = WeixinLogin(APP_ID, APP_SECRET)
         state = state2 + "$$$" + state
         data['url'] = login.authorize(SERVER + "/user/get_code",
                                       'snsapi_base',
                                       state=state)
         response['data'] = data
         return response
     response = import_status("has_opid", "OK")
     return response
Пример #2
0
 def wx_login(self):
     data = request.json
     state_url = data.get('url') or request.url
     logger.debug('get state url %s', state_url)
     state_url = state_url.replace('#', '$').replace('?',
                                                     '~').replace('=', '+')
     state = str(state_url)
     logger.debug('get state %s, len(state) %s', state, len(state))
     login = WeixinLogin(APP_ID, APP_SECRET_KEY)
     redirect_url = login.authorize(QRCODEHOSTNAME +
                                    "/user/wechat_callback",
                                    'snsapi_userinfo',
                                    state=state)
     return {"data": {'redirect_url': redirect_url}, "status": 302}
Пример #3
0
def wx_login(request):
    next_url = request.GET.get('next', '')
    next_url = urlunquote(next_url)

    if request.user.is_authenticated():
        if next_url:
            return HttpResponseRedirect(next_url)
        else:
            raise Http404

    full_url = '%s%s' % (settings.BASE_URL, reverse('weixin:auth'))
    wx_login = WeixinLogin(conf.APP_ID, conf.APP_SECRET)
    login_url = wx_login.authorize(full_url, conf.SCOPE_USERINFO,
                                   urlquote(next_url))
    log.info('weixin login_url: %s' % (login_url))
    return HttpResponseRedirect(login_url)
Пример #4
0
class WxPay(http.Controller):
    def __init__(self):
        self.app_id = config.APPID
        self.app_secret = config.APP_SECRTET
        self.mch_id = config.MCH_ID
        self.mch_key = config.MCH_KEY

        # url处理
        self.encodeURL = config.ENCODE_URL
        # self.URL = config.URL
        self.base_url = config.BASE_URL
        self.notify_url = config.WEIXIN_NOTIFY_URL

        # 初始化
        self.wx_login = WeixinLogin(self.app_id, self.app_secret)
        self.wx_pay = WeixinPay(self.app_id, self.mch_id, self.mch_key,
                                self.notify_url)

    @http.route("/odoo/login/<param>", auth="public", website=True)
    def login(self, param, **kwargs):
        """
        微信获取code
        :param param: 传入参数名(非字典、列表)
        :return:
        """
        redirect_url = self.base_url + param
        openid = request.httprequest.cookies.get("openid")
        next = request.httprequest.args.get("next") or redirect_url
        if openid:
            return request.redirect(next)
        # callback = url_for("authorized", next=next, _external=True)
        callback = self.encodeURL + "?next=" + next
        url = self.wx_login.authorize(
            callback, "snsapi_base")  # 引导用户跳转到授权页面,callback = redirect_uri
        return request.redirect(url)

    @http.route("/odoo/authorized", auth="public", website=True)
    def authorized(self, **kwargs):
        """
        微信验证获取openid
        :return:
        """
        code = request.httprequest.args.get("code")
        if not code:
            return "ERR_INVALID_CODE", 400
        next = request.httprequest.args.get("next")
        data = self.wx_login.access_token(code)  # 通过code换取网页授权access_token
        openid = data.openid
        resp = request.redirect(next)
        expires = datetime.now() + timedelta(days=1)
        resp.set_cookie("openid", openid, expires=expires)
        return resp

    @http.route("/odoo/pay/create", type="json", auth="public", website=True)
    def pay_create(self, **kwargs):
        """
        微信JSAPI创建统一订单,并且生成参数给JS调用
        必填参数:
            out_trade_no 商户订单号
            body 商品描述
            total_fee 商品描述
            openid 用户标识
        """
        # 网页端调起支付API
        try:
            remote_addr = request.httprequest.environ[
                'REMOTE_ADDR']  # 获取远程客户端IP
            openid = request.httprequest.cookies.get("openid")
            out_trade_no = self.wx_pay.nonce_str  # 商户订单号设定为随机字符串
            raw = self.wx_pay.jsapi(openid=openid,
                                    body=u"测试",
                                    out_trade_no=out_trade_no,
                                    total_fee=1,
                                    spbill_create_ip=remote_addr)  # 外部传入openid
            return json.dumps(raw)  # 直接返回包含Json格式数据响应的方法
        except WeixinPayError as e:
            print(e.message)
            return e.message, 400

    @http.route("/odoo/pay/notify", auth="public", website=True)
    def pay_notify(self, **kwargs):
        """
        微信异步通知
        """
        data = self.wx_pay.to_dict(request.data)
        if not self.wx_pay.check(data):
            return self.wx_pay.reply("签名验证失败", False)
        return self.wx_pay.reply("OK", True)  # 处理业务逻辑
Пример #5
0
 def get_login_url(self, scope=wx_conf.SCOPE_USERINFO, state=''):
     url = reverse('weixin:auth', args=[self.name])
     full_url = '%s%s' % (settings.BASE_URL, url)
     wx_login = WeixinLogin(self.app_id, self.app_secret)
     return wx_login.authorize(full_url, scope, state)
Пример #6
0
 def get_login_url(self, scope=wx_conf.SCOPE_USERINFO, state=''):
     url = reverse('weixin:auth', args=[self.name])
     full_url = 'http://%s%s' % (wx_conf.BIND_DOMAIN, url)
     wx_login = WeixinLogin(self.app_id, self.app_secret)
     return wx_login.authorize(full_url, scope, state)