Mexican rule of California was pretty inept. There were several attempted rebellions in the early 1840s, with the final one started in 1846, around the same time as but independent of the Mexican-American War. American forces came in 1846, with Commodore John D. Sloat (I'm surprised SF hasn't renamed Sloat Blvd), and after several battles Mexican Californians gave up, making California American territory in 1847.
In February 1848 the Treaty of Guadalupe Hidalgo ended the Mexican-American War, formalizing the Southwest becoming US territory, with the US paying, IIRC, $18M in gold or silver, with interest added after the first year, and the US assuming Mexican debts from Texas' War of Independence (which had been arbitrated by the UK). About a week before the Treaty of Guadalupe Hidalgo was signed gold was discovered in the Sierras. At the time the treaty was signed, that discovery was not known (no Internet, no telephones, and no telegraph communication to the town of Guadalupe Hidalgo) and the US bought a large territory of pretty much unknown quality.