We present a method that operates an electrolyzer to meet the demand of a hydrogen refueling station in a cost-effective manner by solving a model-based optimal control problem. To formulate the underlying problem, we first conduct an experimental characterization of a Siemens SILYZER 100 polymer electrolyte membrane electrolyzer with \SI{100}{\kilo \watt} of rated power. We run experiments to determine the electrolyzer's conversion efficiency and thermal dynamics as well as the overload-limiting algorithm used in the electrolyzer. The resulting detailed nonlinear models are used to design a real-time optimal controller, which is then implemented on the actual system. Each minute, the controller solves a deterministic, receding-horizon problem which seeks to minimize the cost of satisfying a given hydrogen demand, while using a storage tank to take advantage of time-varying electricity prices and photovoltaic inflow. We illustrate in simulation the significant cost reduction achieved by our method compared to others in the literature, and then validate our method by demonstrating it in real-time operation on the actual system.