$(function(){
    //获取url中的参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }


    var debug = false;

    var g_openid = "";
    if(debug){
        g_openid = "填写要调试的openid即可";
    }

    window.getOpenId = function(cb){
        if (g_openid.length>0){
            cb(g_openid);
        }
        var code = getUrlParam("code");
        $.ajax({
            url: '/wechat/get_open_id',
            data: {code: code},
            type: 'post',
            dataType: 'json',
            success: function(data){
                g_openid = data.openid;
                cb(g_openid);
            },
            error: function(xhr,err){
                alert("认证失败: "+err);
            }
        });
    }
});