Example #1
0
def update_jsapi_ticket():
    try:
        wx_access_token = WxAccessToken.get(WxAccessToken.appid == WX_APP_ID)
    except DoesNotExist:
        raise Exception('Need to get access token before request for jsapi ticket')

    jsapi_ticket_url = create_jsapi_ticket_url(wx_access_token.token)
    ret_text = urlopen(jsapi_ticket_url).read().strip().decode('utf8', 'ignore')
    ret_data = json.loads(ret_text)

    if u'ticket' not in ret_data:
        raise Exception('Error occurs when trying to get jsapi ticket')

    ticket, expire = ret_data[u'ticket'], ret_data[u'expires_in']

    wx_jsapi_ticket, _ = WxJsapiTicket.get_or_create(appid=WX_APP_ID)
    wx_jsapi_ticket.ticket = ticket
    wx_jsapi_ticket.expires_in = expire
    if not wx_jsapi_ticket.save():
        raise Exception('Error occurs when saving jsapi ticket to database')

    print('Get jsapi ticket %s which will expire in %s seconds' % (ticket, expire))
    return ticket, int(expire)