How to programmatically add fields to matrix blocks?
I'm assuming that you're attempting to create the Matrix, with one or more blocks each containing one or more fields, from scratch? I.e. you're not simply trying to populate content into an already defined Matrix?

Going off of that assumption:

PS: Sorry, this code is not based on your code - I simply took working code from one of my other projects.

// Create a field-group to store our Matrix in
$fieldGroup       = new FieldGroupModel();
$fieldGroup-&gt;name = 'My Field Group';
craft()-&gt;fields-&gt;saveGroup($fieldGroup);

// Create the matrix-field itself
$field          = new FieldModel();
$field-&gt;groupId = $fieldGroup-&gt;getAttribute('id');
$field-&gt;name    = 'My Matrix';
$field-&gt;handle  = 'myMatrix';
$field-&gt;type    = 'Matrix';

// Create a rich-text field which we will need later
$textField = ['name' =&gt; 'Text Field',
              'handle'       =&gt; 'label',
              'required'     =&gt; TRUE,
              'instructions' =&gt; '',
              'type'         =&gt; 'RichText',
              'typesettings' =&gt; ['configFile'            =&gt; 'Standard.json',
                                 'cleanupHtml'           =&gt; 1,
                                 'purifyHtml'            =&gt; 1,
                                 'columnType'            =&gt; 'text',          
                                 'availableAssetSources' =&gt; '',
                                 'availableTransforms'   =&gt; '']];

// Define block-types for our Matrix-field
$blockTypes = ['new1' =&gt; ['name'   =&gt; 'My text field',
                          'handle' =&gt; 'myTextField',
                          'fields' =&gt; ['new1' =&gt; $textField]];

// Assign block-types to the Matrix-field
$field-&gt;settings = ['blockTypes' =&gt; $blockTypes];

// Finish the creation of the Matrix-field by saving it
craft()-&gt;fields-&gt;saveField($field)


I've had to adjust the code slightly to not give you the full 125 lines of code I use (mostly due to having a LOT of different block-types with a lot of different fields) - but hopefully you can get the gist of how it's working and solve your issue based on this :)

PPS: It seems like your code should work fine if you only tweak the order in which you do things slightly.


Create Field Group
Create Matrix Field
Define Block Fields
Create Block Types using defined Block Fields
Assign Block Types to Matrix Field
Save Matrix Field