[P:1]([O-:5])([O-:4])([O-:3])=[O:2].[F-:6].[Cl-:7].[NH3:8].[Mg:9]>>[P:1]([O-:5])([O-:4])([O-:3])=[O:2].[NH4+:8].[Mg+2:9].[F-:6].[Mg+2:9].[F-:6].[Cl-:7].[Mg+2:9].[Cl-:7]phosphate and fluoride or chloride ions and buffered with ammonia or an amine to a pH of about 5 to 11, applying a direct current to the bath, and pulsing the direct current, whereby on the surface of the magnesium or its alloy there is formed magnesium ammonium phosphate and magnesium fluoride or magnesium chloride.