Samoa were ahead 6-0 before Wales responded through Jared Rosser's try.
Aled Ward, Sean Moore and two tries from Shane Lewis-Hughes gave Wales a commanding lead
Alexander Pohla-Murray and Setu Enoka crossed for Samoa but Dane Blacker, Will Griffiths and Joe Goodchild sealed a bonus-point win.
Wales had lost their opening two matches against Australia and England in Pool A.
The win with a bonus point was crucial for Wales, as Jason Strange's side now look likely to avoid being among the bottom four teams who will battle to avoid relegation to the second-tier U20 Trophy next year.
Ireland needed to beat New Zealand with a bonus point to overtake Wales in the rankings, but were crushed 69-3 by the junior Kiwis.
Photo by World Rugby
Source:
BBC